<!DOCTYPE html>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>涨停时间轴</title>
		<link href="css/text.css" rel="stylesheet" type="text/css" />
		<style type="text/css">
			p {margin:0px;}
			body {
				background-color: #141212;
			}
			#box{
				display:inline-block;
				margin:0px 5px 0px 80px;
				border-box:50%;
				width:10px;
				height:10px;
			}
			.fixedBox{
				border: 1px solid #555555;
				
			}
			.fixedBox::-webkit-scrollbar {
				width: 10px;
				height: 10px;
			}
      .tabs {
        padding-top: 0px;
        display: flex;
        align-items: center;
        margin-bottom: 0px;
      }
      
      .tabs span {
        cursor: pointer;
        padding: 5px 7px;
        margin-right: 10px;
        background-color: #222222;
        color: #e0e0e0;
        border-radius: 4px;
        transition: background-color 0.3s;
      }
      .filter-dropdown {
        height: 24px;
      }
      .tabs span:hover,
      .tabs .active {
        background-color: #800000;
      }
      #tempTitle {
        margin-bottom: 0;
      }
	.custom-button {
		display: inline-flex; /* 设置为内联弹性盒模型 */
		justify-content: center; /* 水平居中 */
		align-items: center; /* 垂直居中 */
		padding: 1px; /* 根据需要调整内边距 */
		margin-right: 30px;
		margin-top: 0px;
		/* 其他样式，如背景色、边框等 */
	}
	
	.custom-button img {
		/* 调整图片大小或样式 */
		height: 16px; /* 示例值，根据实际需要调整 */
		width: auto; /* 保持图片原始宽高比 */
		vertical-align: middle; /* 对于非flexbox布局，可能需要此属性 */
	}
		</style>
		<script type="text/javascript" src="js/json2html.js"></script>
		<script type="text/javascript" src="js/jquery.min.js"></script>
		<script type="text/javascript" src="DatePicker/WdatePicker.js"> </script>
		<script type="text/javascript" src="js/echarts.js"></script>
	</head>
	<body>
		<div id="towrite" class="fixedBox" style="display:none;">
		<div>
        	<button class="custom-button" onclick="togglePlaySound()"><span id="spanPlaySound" >开</span><img src="res/laba.jpg" class="button-image"></button>
			<audio id="buyAudio" src="res/alert1.mp3" preload="auto"></audio>
			<audio id="sellAudio" src="res/alert2.mp3" preload="auto"></audio>
			<audio id="newLimitUpAudio" src="res/有涨停股.mp3" preload="auto"></audio>
		</div>
      <div class="tabs">
        <span class="tab-main active" onclick="handleClick(0)">全部</span>
        <span class="tab-buy" onclick="handleClick(1)">买单</span>
        <span class="tab-out" onclick="handleClick(2)">卖单</span>
        <select onchange="handleChange()" class="filter-dropdown" id="valueFilter">
          <option value="0">全部</option>
          <option value="1000000">100万</option>
          <option value="3000000">300万</option>
          <option value="5000000">500万</option>
          <option value="10000000">1000万</option>
        </select>
        <select onchange="handleDaysChange()" class="filter-dropdown" id="daysFilter" style="margin-left: 10px;">
          <option value="1">1日</option>
          <option value="2">2日</option>
          <option value="3">3日</option>
          <option value="5">5日</option>
        </select>
        <div id="tempTitle"></div>
      </div>
      <div id="marketInfoContainer" style="display:none; position:absolute; top:0; left:100; right:0; text-align:center; background-color:rgba(30,30,30,0.8); padding:4px 0; z-index:10; border-bottom:1px solid #333; color:#ccc;">
        <div id="marketInfoPanel" style="font-size:12px; line-height:18px;"></div>
      </div>
      <div id="title" style="height:20px;"></div>
			<div id="chart" style="position:relative; float:left;"></div>
			<!-- <div id="towrite1" class="fixedBox" style="position:relative; float:left;margin-top:-18px;"></div> -->
		</div>
		
		<script>
      // 获取数据
	  let codeBigMoneyLastTimeMap = {}; // 股票代码最新大资金时间Map
	  let bigmoneyPlaySoundFlag = false; // 大资金语言播报开关
      var scatterData = []
      let circleType = 0
      let circlePrice = 0
      const fn = (val) => {
        let val1 = val
        if (val1.indexOf("万") != -1) {
          val1 = parseFloat(val1) * 10000;
        } else if (val1.indexOf("亿") != -1) {
          val1 = parseFloat(val1) * 100000000;
        } else {
          val1 = parseFloat(val1);
        }
        return val1
      }

	  const togglePlaySound = () => {
		bigmoneyPlaySoundFlag = !bigmoneyPlaySoundFlag;
		if (bigmoneyPlaySoundFlag) {
			playsound(true)
			let spanPlaySound = document.getElementById('spanPlaySound');
			spanPlaySound.textContent = '关';
		} else {
			let spanPlaySound = document.getElementById('spanPlaySound');
			spanPlaySound.textContent = '开';
		}
	  }

      const playsound = (isbuy) => {
		console.log('playsound')
		let audioId = 'buyAudio';
		if (!isbuy) {
			audioId = 'sellAudio';
		}
		let audioElement = document.getElementById(audioId);
  		audioElement.play();
      }

      const handleClick = (num) => {
        const arrs = ['tab-main', 'tab-buy', 'tab-out']
        arrs.forEach((v, i) => {
          const ele = document.querySelector('.' + v)
          ele.classList.remove('active')
          if (num === i) {
            ele.classList.add('active')
            circleType = i
          }
        })
        v = 1
        getSource()
      }
      const handleChange = (val) => {
        circlePrice = document.querySelector('#valueFilter').value
        v = 1
        getSource()
      }
      const handleDaysChange = () => {
        selectedDays = parseInt(document.querySelector('#daysFilter').value);
        v = 1;
        getSource();
      }

      let selectedDays = 1; // 默认显示1日

      function getScatterData(dm) {
		dest_url = 'http://vaserviece.10jqka.com.cn/Level2/index.php?&op=mainMonitorDetail&stockcode='+dm;
		console.log('getScatterData', dest_url)
        $.ajax({
          url: 'http://vaserviece.10jqka.com.cn/Level2/index.php?&op=mainMonitorDetail&stockcode='+dm,
          type: "get",
          // dataType: "text",
          async : false,
          cache:false,
          timeout:30000,
          success: function(data) {
            const temp = JSON.parse(data)
            scatterData = []
            let listTemp = temp.list
            listTemp = listTemp.filter((v) => {
              return  (circleType !== 0 ? v.tradetype == circleType : true) && (circlePrice !== 0 ? fn(v.value) > circlePrice : true)
            })

			let isbuy = false;
			let bigmoney = false;
			let bigmoneyLastTime = '';
            listTemp.forEach((item) => {
              const curTime = item.ctime.slice(0, 5)
              item.realTime = curTime
              item.realVolumn = Math.floor(item.volume.split('手')[0])
              item.realValue = Math.floor(item.value.split('万')[0])
              item.others = [
                {
                  realVolumn: item.volume,
                  realValue: item.value,
                  nature: item.nature
                }
              ]
              const isBuy = item.tradetype === '1'
			  // 判断是否超过500万
			  if (item.realValue >= 500) {
				bigmoney = true;
			  	isbuy = isBuy;
				bigmoneyLastTime = item.realTime;
				console.log('getScatterData', isbuy, item.realTime, item.realValue, item.realVolumn);
			  }
              if (!isBuy) {
                item.realValue = -item.realValue
                item.realVolumn = -item.realVolumn
              }
              const isExistScatter = scatterData.find(v => v.realTime === curTime)
              if (isExistScatter) {
                isExistScatter.realValue = isExistScatter.realValue + item.realValue
                isExistScatter.realVolumn =  isExistScatter.realVolumn + item.realVolumn
                isExistScatter.others.push({
                  realVolumn: item.volume,
                  realValue: item.value,
                  nature: item.nature
                })
              } else {
                scatterData.push(item)
              }
            })
           
            const fn2 = (val) => {
              val = Math.abs(val)
              let num = 10000
              var sizesValue = ''
              /**
               * 判断取哪个单位
               */
              if(val < 1000){
                // 如果小于1000则直接返回
                sizesValue = ''
                return val
              }else if(val > 1000 && val < 9999){
                sizesValue = '千'
              } else if(val > 10000 && val < 99999999){
                sizesValue = '万'
              } else if(val > 100000000){
                sizesValue = '亿'
              }
              /**
               * 大于一万则运行下方计算
               */
              let i = Math.floor(Math.log(val) / Math.log(num))
              /**
               * toFixed(0)看你们后面想要取值多少，我是不取所以填了0，一般都是取2个值
               */
              var sizes = ((val / Math.pow(num, i))).toFixed(0)
              sizes = sizes + sizesValue
              return sizes
            }
            const temp3 = (fn(temp.title.mainbuy) - fn(temp.title.mainsell)).toFixed(0)
            const temp2 = temp3 < 0 ? '-' + fn2(temp3) : fn2(temp3)
            const tempColor1 = temp3 < 0 ? 'green' : 'red'
            
            // 生成股票信息和竞价链接
            var stockInfo = "";
            var jjLink = "";
            
            if(yy == 1){
                stockInfo = '&nbsp;&nbsp;&nbsp;' + gpdm + "&nbsp;&nbsp;&nbsp;" + gpmc + "&nbsp;&nbsp;&nbsp;" + (selectedDays > 1 ? selectedDays + "日" : rq);
                jjLink = '<a href="javascript:getSource(' + (jk == 0 ? '1' : '0') + ');"  id="jj"  style="padding-left:20px;font-size:14px;">竞价</a>';
            }
            
            // 整合主力信息和股票信息到同一行
            document.getElementById('tempTitle').innerHTML = `主力买：<span style="color:red;margin-right:6px;">${temp.title.mainbuy}</span>主力卖：<span style="color:green;margin-right:6px;">${temp.title.mainsell}</span>主力净：<span style="color:${tempColor1};margin-right:6px;">${temp2}</span>${stockInfo}${jjLink}`;
            
            // 如果启用了竞价链接，设置其颜色
            if(yy == 1 && jjLink != ""){
                var aObj = document.getElementById("jj");
                aObj.style.color = jk == 1 ? "#00FFFF" : "#fff";
            }
			
			// 大资金播放提示音
			if (bigmoney) {
				//  出现大资金比较上次播放时间戳，如果时间戳有变更再播放
				if (!(dm in codeBigMoneyLastTimeMap) || (codeBigMoneyLastTimeMap[dm] < bigmoneyLastTime)) {
					console.log('getSource', dm, bigmoneyLastTime)
					// 更新最新播放时间
					codeBigMoneyLastTimeMap[dm] = bigmoneyLastTime;
					// 如果语音播报开关未打开则不进行播音
					if (bigmoneyPlaySoundFlag) {
						playsound(isbuy);
					}
				}
			}
          },
          error: function(xhr, status, errorThrown) {
            console.log(xhr, status, errorThrown);
          }
        });
      }
			var yy = 1;  //部分显示（小图）；
			window.onload = function() {
				changeStyle();
				getSource(jk);
				// 添加调用市场信息显示函数
				fetchMarketInfo();
			}

			$(function() {
				setInterval(function() {
					getSource(jk);
				},
				300);
			})
			
			function time_range(beginTime, endTime) {
				var strb = beginTime.split(":");
				if (strb.length != 2) {
					return false;
				}

				var stre = endTime.split(":");
				if (stre.length != 2) {
					return false;
				}

				var b = new Date();
				var e = new Date();
				var n = new Date();

				b.setHours(strb[0]);
				b.setMinutes(strb[1]);
				e.setHours(stre[0]);
				e.setMinutes(stre[1]);

				console.log('time_range', n.getTime(), b.getTime(), e.getTime());　　　　　　
				if (n.getTime() - b.getTime() > 0 && n.getTime() - e.getTime() < 0) {
					v = 1;
					console.log('time_range', true);　　　　　　
					return true;
				} else {
					console.log('time_range', false);
				    return false;
				}
			}　　　
   　　　
			function changeStyle() {
				var div = document.getElementById("towrite");
				div.style.display= "block";
				//div.style.border= "1px solid #fff";
				div.style.border= "none";
				div.style.marginTop= "-10px";
				div.style.left= "0px";
				div.style.width= "100%";
				div.style.height= "100%";
				div.style.fontSize="12px";
				
				var div1 = document.getElementById("chart");
				div1.style.border= "1px solid #696969";
				div1.style.marginTop= "-10px";
				div1.style.left= "0px";
				div1.style.width= "99%";
				
				// 对于上证指数，调整图表高度为更合适的值
				if(gpdm == "999999"){
					div1.style.height= "100vh"; // 使用视口高度单位
				} else {
					div1.style.height= "99%";
				}
				
				// 注释掉的代码，改为正确的JavaScript注释格式
				// var div2 = document.getElementById("towrite1");
				// div2.style.border= "1px solid #696969";
				// div2.style.left= "0px";
				// div2.style.width= "90%";
				// div2.style.height= "30%";
			}
			
			Date.prototype.Format = function (fmt) {
				var o = {
				"M+": this.getMonth() + 1, //月份
				"d+": this.getDate(), //日
				"h+": this.getHours(), //小时
				"m+": this.getMinutes(), //分
				"s+": this.getSeconds(), //秒
				"q+": Math.floor((this.getMonth() + 3) / 3), //季度
				"S": this.getMilliseconds() //毫秒
				};
				if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
				for (var k in o)
				if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
				return fmt;
			};
			
			function keepTwoDecimal(num) {
               var result = parseFloat(num);
               if (isNaN(result)) {
                   return false;
               }
               result = Math.round(num * 100) / 100;
               return result;
			}
			
			function NumberTransform(num) {
				var result = num;
				if(Math.abs(num) > 100000000){
					result = num / 100000000;
					result = result.toFixed(0) + "亿";
				}else if(Math.abs(num) > 10000){
					result = num/10000;
					result = result.toFixed(0) + "万";
				}
				return result;
			};
			
			var z = 0;  //刷新
			var v = 0;	//刷新
			var gpdm = "";
			var gpmc = "";
			var rq = "";
			var preClose = 0;	//昨收盘
			var jk = 0;  //默认是否显示竞价
			function getSource(p) {
				var u = decodeURI(window.location.href);
				var dm = "";
				if(u.indexOf("##") > -1){
					var gp = u.split('##');
					dm = gp[1];
					gpmc = gp[2];
					if(gp[3] != undefined){
						yy = gp[3];
					}
				}
				if (dm == 'xxxxxx' || dm == ''){
					dm = "999999";
					gpmc = "上证指数";
				}
				
				console.log('getSource', dm, gpdm, v, p, jk, selectedDays);
				if(dm != gpdm || v == 1 || p != jk){
					//alert(p)
					console.log('dm != gpdm || v == 1 || p != jk');
					v = 0;
					jk = p;
					gpdm = dm;
					var dms = "";
					var dmt = "";
					if(dm.substr(0,1)=="6"){
						dms = "SH" + dm;
						dmt = "1." + dm;
					}else{
						dms = "SZ" + dm;
						dmt = "0." + dm;
					}
					
					if(dm == "999999"){
						dmt = "1.000001";
					}else if(dm.substr(0,3)=="399"){
						dmt = "0." + dm;
					}
					
					var url ="http://push2his.eastmoney.com/api/qt/stock/trends2/get?fields1=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13&fields2=f51,f52,f53,f54,f55,f56,f57,f58&ndays=" + selectedDays + "&secid=" + dmt;
					var res = [];
					$.ajax({
						type: "get",
						url: url,
						dataType: "json",
						async : false,
						cache:false,
						timeout:3000,
						success: function(data) {
							//alert(JSON.stringify(data))
							//document.write(JSON.stringify(data));
							preClose = data.data.preClose;
							var arr = data.data.trends;
							//document.write(JSON.stringify(arr));
							
							// 保存日期标记，用于在图表上标记不同日期
							let dateBoundaries = [];
							let currentDate = "";
							
							for (var i = 0; i < arr.length; i++){
								var aa = arr[i].split(',');
								let timeStr = aa[0].split(" ");
								let dateStr = timeStr[0];
								let timeOnly = timeStr[1];
								
								// 记录日期边界
								if(dateStr !== currentDate) {
									currentDate = dateStr;
									if(i > 0) {
										dateBoundaries.push({
											index: i,
											date: dateStr
										});
									}
								}
								
								if(i == 0){
									rq = dateStr;
								}
								
								if(jk == 0){
									if(Number(timeOnly.replace(":","")) >= 930){
										var rc = {"time": timeOnly, "date": dateStr, "fullTime": aa[0], "open":Number(aa[1]),"close":Number(aa[2]),"high":Number(aa[3]),"low":Number(aa[4]),"vol":Number(aa[5]),"jprice":Number(aa[7])}
										res.push(rc);
									}
								}else{
									var rc = {"time": timeOnly, "date": dateStr, "fullTime": aa[0], "open":Number(aa[1]),"close":Number(aa[2]),"high":Number(aa[3]),"low":Number(aa[4]),"vol":Number(aa[5]),"jprice":Number(aa[7])}
									res.push(rc);
								}
							}
							
							// 将日期边界保存到全局，供图表使用
							window.dateBoundaries = dateBoundaries;
						}
					})
          			getScatterData(dm)
					
					// 将原有的title div高度设为0，避免空白
					var div = document.getElementById('title');
					div.style.height = "0px";
					
					GetChart(res);
					
					// 如果是上证指数，立即刷新市场信息
					if(dm == "999999") {
						fetchMarketInfo();
					}
				} else {
					//console.log('getSource', z);
					z++;
					if(z == 60){
						z = 0;
						time_range("9:00","15:15")  //刷新数据
						//time_range("9:00","23:15")  //测试, 刷新数据
					}
				}
			}
			
			function getParamValues(name, arr) {
				var ret = []
				// 调整数据点长度计算方式，使其更精确对应实际交易数据
				var len = 240 * selectedDays; // 一天交易时间为240个点(4小时，每分钟1个点)
				if(jk == 0){
					len = 240 * selectedDays; // 不包含竞价的话保持240个点
				}
				
				// 使用实际数据长度而不是固定值，防止出现多余空白
				len = Math.min(len, arr.length + 5); // 实际数据长度加少量余量
				
				// 获取日期边界索引，用于在多日视图中断开均价线
				let dateBoundaryIndices = [];
				if(selectedDays > 1 && window.dateBoundaries && window.dateBoundaries.length > 0 && (name === "jprice" || name === "close")) {
					dateBoundaryIndices = window.dateBoundaries.map(boundary => boundary.index);
				}
				
				for (var i = 0; i < len; i++) {
					if(arr[i] != undefined){
						// 如果是均价(jprice)或价格(close)且处于多日模式，检查是否是日期边界点
						if((name === "jprice" || name === "close") && selectedDays > 1 && dateBoundaryIndices.includes(i)) {
							// 在日期边界处插入null值，使线条断开
							ret.push(null);
						} else {
							ret.push(arr[i][name]);
						}
					}else{
						ret.push(null);
					}
				}
				return ret;
			}
			
			// 计算移动平均线函数
			function calculateMA(data, period) {
				var result = [];
				// 获取日期边界索引，用于在多日视图中断开均线
				let dateBoundaryIndices = [];
				if(selectedDays > 1 && window.dateBoundaries && window.dateBoundaries.length > 0) {
					dateBoundaryIndices = window.dateBoundaries.map(boundary => boundary.index);
				}
				
				for (var i = 0; i < data.length; i++) {
					// 如果处于多日模式且当前点是日期边界，则插入null使线条断开
					if(selectedDays > 1 && dateBoundaryIndices.includes(i)) {
						result.push(null);
						continue;
					}
					
					if (i < period - 1) {
						// 数据不足以计算MA时返回null
						result.push(null);
						continue;
					}
					
					var sum = 0;
					var count = 0;
					// 向前计算period个值的平均
					for (var j = 0; j < period; j++) {
						if (i - j >= 0 && data[i - j] !== null && data[i - j] !== undefined) {
							sum += data[i - j];
							count++;
						}
					}
					// 只有当有足够的有效数据时才计算平均值
					result.push(count > 0 ? sum / count : null);
				}
				return result;
			}
			
			function ratioCalculate(price, yclose) {  //涨跌幅
			  return ((price - yclose) / yclose * 100).toFixed(2);
			}
			
			// 计算滚动30分钟窗口内的最高点和最低点
			function calculateRollingHighLow(arr, minutes) {
				// 每个交易日假设有4小时交易时间，每分钟一个点，总共240个点
				// 30分钟窗口对应30个数据点
				const windowSize = minutes; // 使用传入的参数，通常是30分钟
				const result = {
					highPoints: [],  // 存储最高点
					lowPoints: [],   // 存储最低点
					highBreakPoints: [], // 存储突破最高点的位置
						lowBreakPoints: []   // 存储突破最低点的位置
				};
				
				// 如果数据不足，添加一些测试数据确保线条显示
				if (!arr || arr.length < windowSize) {
					console.log('数据不足，添加测试数据');
					// 添加测试数据点，确保有线条显示
					if (arr && arr.length > 10) {
						const startIdx = 5;
						const endIdx = arr.length - 5;
						const midValue = arr[Math.floor(arr.length/2)]?.close || 0;
						
						// 添加一个高点示例
						result.highPoints.push({
							coord: [startIdx, midValue * 1.01],
							value: midValue * 1.01,
							ongoing: true,
							symbolSize: 0
						});
						
						result.highPoints.push({
							coord: [endIdx, midValue * 1.01],
							value: midValue * 1.01,
							ongoing: true,
							symbolSize: 0
						});
						
						// 添加一个低点示例
						result.lowPoints.push({
							coord: [startIdx, midValue * 0.99],
							value: midValue * 0.99,
							ongoing: true,
							symbolSize: 0
						});
						
						result.lowPoints.push({
							coord: [endIdx, midValue * 0.99],
							value: midValue * 0.99,
							ongoing: true,
							symbolSize: 0
						});
					}
					return result;
				}
				
				// 遍历数据，计算滚动窗口的最高点和最低点
				let prevHighVal = -Infinity;
				let prevLowVal = Infinity;
				let prevHighIdx = -1;
				let prevLowIdx = -1;
				let isHighLineContinue = true;
				let isLowLineContinue = true;
				
				// 遍历每个时间点
				for (let i = windowSize; i < arr.length; i++) {
					// 如果没有足够的数据点，跳过
					if (!arr[i]) {
						continue;
					}
					
					// 查找窗口内的最高点和最低点 [i-windowSize, i-1]
					let windowHighVal = -Infinity;
					let windowLowVal = Infinity;
					let windowHighIdx = -1;
					let windowLowIdx = -1;
					
					for (let j = i - windowSize; j < i; j++) {
						if (j < 0 || !arr[j]) continue;
						
						// 排除竞价阶段的数据点 (9:15-9:20)
						// 判断当前点是否是今天的竞价阶段数据
						let isAuctionPeriod = false;
						
						// 首先确认时间格式
						if (arr[j].time) {
							// 如果是当天（而不是多日视图中的前几天）且时间在9:15-9:20之间
							if (!selectedDays || selectedDays === 1 || 
							   (selectedDays > 1 && arr[j].date === arr[arr.length-1].date)) {
								// 判断时间是否在9:15-9:20之间
								const timeValue = arr[j].time.replace(':', '');
								if (timeValue >= '915' && timeValue <= '920') {
									isAuctionPeriod = true;
								}
							}
						}
						
						// 跳过竞价阶段的数据点
						if (isAuctionPeriod) {
							continue;
						}
						
						// 尝试获取高点和低点
						let highValue = arr[j].high;
						let lowValue = arr[j].low;
						
						// 如果high/low不存在，使用close
						if (highValue === undefined || highValue === null) {
							highValue = arr[j].close;
						}
						
						if (lowValue === undefined || lowValue === null) {
							lowValue = arr[j].close;
						}
						
						// 更新窗口内的最高点
						if (highValue > windowHighVal) {
							windowHighVal = highValue;
							windowHighIdx = j;
						}
						
						// 更新窗口内的最低点
						if (lowValue < windowLowVal) {
							windowLowVal = lowValue;
							windowLowIdx = j;
						}
					}
					
					// 获取当前收盘价
					let currentClose = arr[i].close;
					if (currentClose === undefined || currentClose === null) {
						continue; // 如果没有有效的收盘价，跳过
					}
					
					// 只有在找到有效的高低点时才处理
					if (windowHighIdx >= 0 && windowLowIdx >= 0) {
						// 检查是否有新的最高点
						if (windowHighVal > prevHighVal || prevHighIdx < 0) {
							prevHighVal = windowHighVal;
							prevHighIdx = windowHighIdx;
							isHighLineContinue = true;
							// 添加新的最高点
							result.highPoints.push({
								coord: [prevHighIdx, prevHighVal],
								value: prevHighVal,
								ongoing: true,
								symbolSize: 0 // 不显示标记
							});
						}
						
						// 检查是否有新的最低点
						if (windowLowVal < prevLowVal || prevLowIdx < 0) {
							prevLowVal = windowLowVal;
							prevLowIdx = windowLowIdx;
							isLowLineContinue = true;
							// 添加新的最低点
							result.lowPoints.push({
								coord: [prevLowIdx, prevLowVal],
								value: prevLowVal,
								ongoing: true,
								symbolSize: 0 // 不显示标记
							});
						}
						
						// 检查当前价格是否突破前高
						if (isHighLineContinue && currentClose > prevHighVal) {
							isHighLineContinue = false;
							// 标记突破点 - 修改：箭头显示在水平线上，而不是当前价格位置
							result.highBreakPoints.push({
								coord: [i, prevHighVal], // 修改y坐标为前高值，而不是当前价格
								value: '突破',
								itemStyle: {
									color: '#FF0000' // 红色
								},
								symbol: 'arrow',
								symbolSize: 10,
								symbolRotate: 0 // 向上箭头
							});
							
							// 更新最高点信息，标记为不再继续
							const lastHighPoint = result.highPoints[result.highPoints.length - 1];
							if (lastHighPoint) {
								lastHighPoint.ongoing = false;
								result.highPoints.push({
									coord: [i, prevHighVal],
									value: prevHighVal,
									ongoing: false,
									symbolSize: 0 // 不显示标记
								});
							}
						}
						
						// 检查当前价格是否突破前低
						if (isLowLineContinue && currentClose < prevLowVal) {
							isLowLineContinue = false;
							// 标记突破点 - 修改：箭头显示在水平线上，而不是当前价格位置
							result.lowBreakPoints.push({
								coord: [i, prevLowVal], // 修改y坐标为前低值，而不是当前价格
								value: '突破',
								itemStyle: {
									color: '#00FF00' // 绿色
								},
								symbol: 'arrow',
								symbolSize: 10,
								symbolRotate: 180 // 向下箭头
							});
							
							// 更新最低点信息，标记为不再继续
							const lastLowPoint = result.lowPoints[result.lowPoints.length - 1];
							if (lastLowPoint) {
								lastLowPoint.ongoing = false;
								result.lowPoints.push({
									coord: [i, prevLowVal],
									value: prevLowVal,
									ongoing: false,
									symbolSize: 0 // 不显示标记
								});
							}
						}
						
						// 如果高点线和低点线都继续延伸，添加当前点
						if (isHighLineContinue) {
							result.highPoints.push({
								coord: [i, prevHighVal],
								value: prevHighVal,
								ongoing: true,
								symbolSize: 0 // 不显示标记
							});
						}
						
						if (isLowLineContinue) {
							result.lowPoints.push({
								coord: [i, prevLowVal],
								value: prevLowVal,
								ongoing: true,
								symbolSize: 0 // 不显示标记
							});
						}
					}
				}
				
				return result;
			}
			
		</script>
		<script>
			function GetChart(arr) {
				// 板数数字转中文
				function numToChinese(num) {
					const map = {1:'一',2:'二',3:'三',4:'四',5:'五',6:'六',7:'七',8:'八',9:'九',10:'十'};
					return map[num] || num;
				}

				// 获取涨停股票信息
				function getLimitUpStocks(callback) {
					const baseUrl = 'https://apphq.longhuvip.com/w1/api/index.php';
					const params = {
						Order: '0',
						a: 'DailyLimitPerformance', 
						st: '100',
						apiv: 'w21',
						Type: '4',
						c: 'HomeDingPan',
						PhoneOSNew: '1'
					};
					
					// 所有板数
					const pidTypes = [
						{type: '5', board: 5},
						{type: '4', board: 4}, 
						{type: '3', board: 3},
						{type: '2', board: 2},
						{type: '1', board: 1}
					];
					
					let limitUpStocks = [];
					let finished = 0;
					
					// 添加日志
					console.log('开始获取涨停数据...');
					
					pidTypes.forEach(({type, board}) => {
						const url = `${baseUrl}?${Object.entries({...params, PidType: type})
							.map(([key, value]) => `${key}=${value}`)
							.join('&')}`;
						
						console.log(`请求${board}板数据, URL:`, url);
						
						$.ajax({
							url: url,
							type: "get",
							async: true,
							timeout: 10000, // 设置10秒超时
							success: function(data) {
								try {
									if (data && data.info && Array.isArray(data.info[0])) {
										data.info[0].forEach(stock => {
											// 确保时间格式统一
											const timestamp = parseInt(stock[4]);
											if (isNaN(timestamp)) {
												console.warn('无效的时间戳:', stock[4]);
												return;
											}
											
											const timeStr = formatTime(timestamp);
											const stockInfo = {
												code: stock[0],
												name: stock[1],
												time: timestamp,
												timeStr: timeStr,
												reason: stock[5] || '',
												boardCount: board
											};
											
											limitUpStocks.push(stockInfo);
											console.log(`添加涨停股: ${board}板 ${stock[1]} ${timeStr}`);
										});
									} else {
										console.warn(`${board}板数据格式异常:`, data);
									}
								} catch (e) {
									console.error(`${board}板数据处理错误:`, e);
								}
								
								finished++;
								if (finished === pidTypes.length) {
									console.log('涨停数据获取完成, 总数:', limitUpStocks.length);
									// 按时间排序
									limitUpStocks.sort((a, b) => a.time - b.time);
									callback(limitUpStocks);
								}
							},
							error: function(xhr, status, error) {
								console.error(`${board}板数据请求失败:`, status, error);
								finished++;
								if (finished === pidTypes.length) {
									console.log('涨停数据获取完成(部分失败), 总数:', limitUpStocks.length);
									// 按时间排序
									limitUpStocks.sort((a, b) => a.time - b.time);
									callback(limitUpStocks);
								}
							}
						});
					});
				}

				// 格式化时间戳为时分秒
				function formatTime(timestamp) {
					const date = new Date(timestamp * 1000);
					const hours = date.getHours().toString().padStart(2, '0');
					const minutes = date.getMinutes().toString().padStart(2, '0');
					const seconds = date.getSeconds().toString().padStart(2, '0');
					return `${hours}:${minutes}:${seconds}`;
				}

				// 辅助函数用于创建标记线
				function createMarkLinesFromPoints(points) {
					if (!points || points.length < 2) return [];
					
					const markLines = [];
					let startPoint = null;
					let prevOngoing = true;
					
					for (let i = 0; i < points.length; i++) {
						const point = points[i];
						
						// 如果这是起点或者前一个点的状态是不同的，设置新的起点
						if (startPoint === null || prevOngoing !== point.ongoing) {
							startPoint = point;
							prevOngoing = point.ongoing;
							continue;
						}
						
						// 如果当前点和前一个点状态一致，且我们已经有了起点
						if (i === points.length - 1 || point.ongoing !== points[i + 1].ongoing) {
							// 只有当起点和终点的x坐标不同，才添加标记线
							if (startPoint.coord[0] !== point.coord[0]) {
								// 关键修改：创建连续的价格线，而不是水平线
								// 对于高点/低点，使用固定的y值使其显示为水平线
								markLines.push([
									{ 
										coord: [startPoint.coord[0], startPoint.coord[1]],
										lineStyle: { 
											width: 1.5 // 增加线条宽度为1.5，使其更明显
										}
									},
									{ 
										// 关键修改：保持y坐标相同以创建水平线效果
										coord: [point.coord[0], startPoint.coord[1]],
										lineStyle: {
											width: 1.5 // 增加线条宽度为1.5，使其更明显
										}
									}
								]);
							}
							
							// 重置起点
							startPoint = null;
						}
					}
					
					// 如果数据点太少，添加测试数据展示线条
					if (markLines.length === 0 && points.length > 0) {
						// 添加一条固定的水平测试线
						const firstPoint = points[0];
						const lastPoint = points[points.length - 1];
						if (firstPoint && lastPoint) {
							markLines.push([
								{ 
									coord: [firstPoint.coord[0], firstPoint.coord[1]],
									lineStyle: { 
										width: 1.5 // 增加线条宽度为1.5，使其更明显
									}
								},
								{ 
									coord: [lastPoint.coord[0], firstPoint.coord[1]], // 保持y坐标相同
									lineStyle: {
										width: 1.5 // 增加线条宽度为1.5，使其更明显
									}
								}
							]);
						}
					}
					
					return markLines;
				}

				// 获取涨停板信息并渲染图表
				getLimitUpStocks(function(limitUpStocks) {
					let timeGroup = {};
					let earlyTimeGroup = {}; // 专门存储竞价期间的涨停股票
					
					// 只在上证指数时处理涨停数据
					if(gpdm === "999999") {
						console.log('开始处理涨停数据分组...');
						
						limitUpStocks.forEach(stock => {
							// 从timeStr中提取HH:mm格式
							let timeKey = stock.timeStr.slice(0,5);
							const formattedTimeKey = timeKey; // 确保formattedTimeKey变量已定义

							// 确保timeKey格式正确
							if (!/^\d{2}:\d{2}$/.test(timeKey)) {
								console.warn('无效的时间格式:', timeKey, stock);
								return;
							}
							
							// 判断是否是竞价期间的涨停
							const timeValue = Number(timeKey.replace(':', ''));
							if (timeValue >= 925 && timeValue <= 930) {
								// 竞价期间的涨停股票，存入earlyTimeGroup
								if (!earlyTimeGroup[timeKey]) {
									earlyTimeGroup[timeKey] = [];
								}
								earlyTimeGroup[timeKey].push(stock);
								console.log(`竞价期间分组: ${timeKey} - ${stock.boardCount}板 ${stock.name}`);
							} else {
								// 正常交易时段的涨停股票
								if (!timeGroup[timeKey]) {
									timeGroup[timeKey] = [];
								}
								timeGroup[timeKey].push(stock);
								console.log(`分组: ${timeKey} - ${stock.boardCount}板 ${stock.name}`);
							}
						});
						
						// 对每个时间点的股票按板数排序
						Object.keys(earlyTimeGroup).forEach(timeKey => {
							earlyTimeGroup[timeKey].sort((a, b) => {
								// 首先按板数降序
								if (b.boardCount !== a.boardCount) {
									return b.boardCount - a.boardCount;
								}
								// 板数相同时按时间升序
								return a.time - b.time;
							});
							
							console.log(`竞价时间点 ${timeKey} 排序后:`, 
								earlyTimeGroup[timeKey].map(s => `${s.boardCount}板${s.name}`).join(', '));
						});
						
						Object.keys(timeGroup).forEach(timeKey => {
							timeGroup[timeKey].sort((a, b) => {
								// 首先按板数降序
								if (b.boardCount !== a.boardCount) {
									return b.boardCount - a.boardCount;
								}
								// 板数相同时按时间升序
								return a.time - b.time;
							});
							
							console.log(`时间点 ${timeKey} 排序后:`, 
								timeGroup[timeKey].map(s => `${s.boardCount}板${s.name}`).join(', '));
						});
					}

					var res = getParamValues("close", arr);
					
					// 计算MA250均线数据
					var ma250Data = calculateMA(res, 250);
					
					// 计算滚动30分钟窗口的最高点和最低点
					var rollingHighLow = calculateRollingHighLow(arr, 30); // 明确传入30分钟
					
					//过滤null并记录日志
					console.log('开始处理价格数据...');
					var values = arr.map(function(o){
						return o.close;
					}).filter(function(val) {
						return val !== null;
					});
					
					if (values.length === 0) {
						console.warn('没有有效的价格数据');
						return;
					}
					
					console.log(`处理了 ${values.length} 个有效价格点`);
					
					var maxa = Math.max(...values);
					var mina = Math.min(...values);
					console.log(`最高价: ${maxa}, 最低价: ${mina}, 昨收: ${preClose}`);
					
					var zfa = Math.abs((maxa / preClose - 1));
					var zfb = Math.abs((mina / preClose - 1));
					console.log(`最大涨幅: ${(zfa*100).toFixed(2)}%, 最大跌幅: ${(zfb*100).toFixed(2)}%`);
					
					function min() {
						// 为上证指数扩大Y轴范围，确保小盘股指数走势能完整显示
						if(gpdm == "999999"){
							// 获取均价数据
							const jpriceValues = arr.map(o => o.jprice).filter(val => val !== null);
							if (jpriceValues.length === 0) {
								// 使用最大涨跌幅的绝对值来确保对称
								const maxChange = Math.max(zfa, zfb);
								return Number(preClose * (1 - maxChange * 1.1)).toFixed(2);
							}
							// 计算均价的最大涨跌幅
							const maxJPrice = Math.max(...jpriceValues);
							const minJPrice = Math.min(...jpriceValues);
							const jZfa = Math.abs((maxJPrice / preClose - 1));
							const jZfb = Math.abs((minJPrice / preClose - 1));
							// 使用最大变化幅度来确保对称
							const maxChange = Math.max(jZfa, jZfb, zfa, zfb);
							return Number(preClose * (1 - maxChange * 1.1)).toFixed(2);
						} else {
							// 使用最大涨跌幅的绝对值来确保对称
							const maxChange = Math.max(zfa, zfb);
							return Number(preClose * (1 - maxChange)).toFixed(2);
						}
					}
					function max() {
						// 为上证指数扩大Y轴范围，确保小盘股指数走势能完整显示
						if(gpdm == "999999"){
							// 获取均价数据
							const jpriceValues = arr.map(o => o.jprice).filter(val => val !== null);
							if (jpriceValues.length === 0) {
								// 使用最大涨跌幅的绝对值来确保对称
								const maxChange = Math.max(zfa, zfb);
								return Number(preClose * (1 + maxChange * 1.1)).toFixed(2);
							}
							// 计算均价的最大涨跌幅
							const maxJPrice = Math.max(...jpriceValues);
							const minJPrice = Math.min(...jpriceValues);
							const jZfa = Math.abs((maxJPrice / preClose - 1));
							const jZfb = Math.abs((minJPrice / preClose - 1));
							// 使用最大变化幅度来确保对称
							const maxChange = Math.max(jZfa, jZfb, zfa, zfb);
							return Number(preClose * (1 + maxChange * 1.1)).toFixed(2);
						} else {
							// 使用最大涨跌幅的绝对值来确保对称
							const maxChange = Math.max(zfa, zfb);
							return Number(preClose * (1 + maxChange)).toFixed(2);
						}
					}
					
					var _interval = ((preClose-min()) / 4);
					var left = "5%";
					var right = "8%";
					var fsize = "14";
					var show = true;
					if(yy == 0){
						_interval = ((preClose-min()) / 2);
						left = "3%";
						right = "5%";
						fsize = "12";
						show = false;
					}
					
					// 对于多日显示模式，减少右侧边距，使图表能更好地利用空间
					if(selectedDays > 1) {
						right = "5%";
					}
					
					var jm = "09:30";
					if(jk == 0){
						jm = "";
					}
					function getScatterSourceData (arr) {
						const time = getParamValues("time", arr);
						const close = getParamValues("close", arr);
						
						// 在多日模式下，需要将时间映射到正确的日期
						time.forEach((v, i) => {
							if (selectedDays > 1 && arr[i]) {
								// 创建一个复合键，使用日期+时间
								const dateTimeKey = arr[i].date + ' ' + v;
								// 查找当前时间点是否有大单数据
								const isExist = scatterData.find(scatter => scatter.realTime === v);
								if (isExist) {
									close[i] = arr[i].close; // 确保在正确的点上显示大单标记
								} else {
									close[i] = 0;
								}
							} else {
								// 原有单日逻辑
								const isExist = scatterData.find(scatter => scatter.realTime === v);
								if (isExist) {
									// 保持原样
								} else {
									close[i] = 0;
								}
							}
						});
						return close;
					}
					var myChart = echarts.init(document.getElementById('chart'));
					const upColor = '#ec0000';//00da3c
					const downColor = '#00FFFF';//ec0000
					var top2 = 68;
					var top21 = top2 - 3;

					// 准备日期分隔线
					let markLines = [];
					if (selectedDays > 1 && window.dateBoundaries && window.dateBoundaries.length > 0) {
						window.dateBoundaries.forEach(boundary => {
							markLines.push({
								xAxis: boundary.index,
								label: {
									show: false,
									formatter: boundary.date,
									position: 'middle',
									color: '#ffffff',
									fontSize: 10,
									backgroundColor: 'rgba(70,70,70,0.3)',
									padding: [2, 4]
								},
								lineStyle: {
									color: '#cccccc',  // 修改为浅灰色
									type: 'dashed',
									width: 0.2        // 将线条变得更细
								}
							});
						});
					}

					// 对于上证指数调整网格高度与位置
					var gridConfig;
					if(gpdm == "999999"){
						gridConfig = [
							{
								top: '3%',
								left: left,
								right: right,
								height: '80%'  // 增加主图高度
							},
							{
								top: '3%',
								left: left,
								right: right,
								height: '80%'  // 增加主图高度
							},
							{
								top: '84%',    // 调整成交量位置
								left: left,
								right: right,
								height: '10%'  // 减小成交量区域高度
							}
						];
					} else {
						gridConfig = [
							{
								top: '3%',
								left: left,
								right: right,
								height: '58%'
							},
							{
								top: '3%',
								left: left,
								right: right,
								height: '58%'
							},
							{
								top: top2 + "%",
								left: left,
								right: right,
								height: '20%'
							}
						];
					}
					
					var option = {
						animation: false, //取消动画效果
						title: [
							{
								left: 'left',
								//text: '分时图'
							},
							{
								left: 'left',
								//text: '分时图'
							},
							{
								show: show,
								top: gpdm == "999999" ? "72%" : (top21 + "%"),
								left: 'left',
								text: '成交量',
								textStyle: {
									color: "#fff", // 文字的颜色。
									fontSize: fsize,
								}
							}
						],
						tooltip: {   //提示框
							show: show,
							trigger: 'axis',
							position: function (point, params, dom, rect, size) {
								// point: 鼠标位置
								// params: 当前数据信息
								// dom: tooltip DOM 节点
								// rect: 图表容器大小
								// size: tooltip 大小

								// 计算并返回一个数组，表示 tooltip 的 x 和 y 坐标
								return [point[0], point[1]];
							},
							formatter(params) {  //添加文字
								//alert(JSON.stringify(params))
								//document.write(JSON.stringify(params[0]));
								var str = '';
								
								// 在多日分时图中，显示日期
								if (selectedDays > 1 && arr[params[0].dataIndex]) {
									str = arr[params[0].dataIndex].date + ' ';
								}
								
								str += params[0].name + '<br>';
								
								if(params[0].name != "null"){
									params.forEach(item => {
										var name = item.seriesName;
										var c = '<span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;left:5px;background-color:' + item.color + '"></span>';
										if(name == "分时"){
											str += c + '价格:' + item.data + "<br>";
											str += c + '涨幅:' + ratioCalculate(item.data, preClose) + "%<br>";
										}else if(name == "分时均价"){
											str += c + '均价:' + item.data + "<br>";
										}else if(name.indexOf("成交量") > -1){
											str += c + item.seriesName + " : " + item.data + "<br>";
										} else if(item.componentSubType === 'scatter') {
											// 展示主力买卖汇总和明细
											const temp = scatterData.find(v => v.realTime === item.axisValue)
											if (temp && temp.others) {
												const redSpan = '<span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;left:5px;background-color:red"></span>';
												const greenSpan = '<span style="display:inline-block;margin-right:5px;border-radius:50%;width:10px;height:10px;left:5px;background-color:green"></span>';
												buyTotal = 0;
												sellTotal = 0;
												strTotal = '';
											  	strDetail = '';
												index = 0;
												totals = temp.others.length;

											  	temp.others.forEach((temp) => {									
												
													let isbuy = temp.nature.includes('买');
													let realValue = Math.floor(temp.realValue.split('万')[0])
													//if (realValue < 100) return;
													//if (totals > 20 && realValue < 300) return;
													if (isbuy) {
														buyTotal += realValue;
														if (index > 20){
															strDetail += redSpan + temp.realValue;
															return; 
														}else{
															strDetail += redSpan + temp.nature + " : " + temp.realValue  + "<br>";
														}												

													} else {
														sellTotal += realValue;
														if (index > 20){
															strDetail += greenSpan + temp.realValue;
															return; 
														}else{
															strDetail += greenSpan + temp.nature + " : " + temp.realValue  + "<br>";
														}
													}

													index++;

											  	});
												if (buyTotal>0) {
													strTotal += redSpan+'主力买总 : '+buyTotal+"万<br>";
												}
												if (sellTotal>0) {
													strTotal += greenSpan+'主力卖总 : '+sellTotal+"万<br>";
												}
												str += strTotal;
												str += strDetail;
											}
										}
									});
									return str;
								}
							}
						},
						grid: gridConfig,
						xAxis: [
							{
								//type: 'category',
								gridIndex: 0,
								data: getParamValues("time", arr),
								axisLine: { show: false	}, //x轴坐标线设置
								axisTick: { show: false },
								splitLine: { show: false },
								axisLabel: { show: false },
							},
							{
								show: false,
								gridIndex: 1,
								data: getParamValues("time", arr),
								axisPointer: {show: false},
							},
							{
								type: 'category',
								gridIndex: 2,                    //对应坐标轴所在grid的索引
								data: getParamValues("time", arr),
								axisTick: { show: false },
								axisLine:{  //x轴坐标线设置
									lineStyle:{
										color:"#808080",  //x轴坐标线颜色
										width: 1   // 坐标轴线宽
									}
								},
								axisLabel:{	 //x轴标签设置
									showMaxLabel:true, //显示最大 tick(最后一天)
									interval: 0,
									//padding: [0, 0, 0, 30],
									formatter: function (value, index) {
										// 多日分时图下，只在每日开始和结束时展示时间
										if (selectedDays > 1) {
											let dailyPoints = 240; // 一天的数据点数
											let dayIndex = Math.floor(index / dailyPoints);
											let dayPosition = index % dailyPoints;
											// 只在每日开始、中间和结束位置显示时间标签
											if (dayPosition === 0 || dayPosition === 120 || dayPosition === 239) {
												return value;
											}
											return '';
										} else {
											// 原有的单日逻辑
											var c = index % 15;
											if(yy == 0){
												c = index % 60;
											}
											if(value != "null" && c == 0){
												return value;
											}
										}
									},
									textStyle:{  //x轴文字
										color:"#FFF"
									}
								}
							}
						],
						yAxis: [
							{
								type: 'value',
								gridIndex: 0,
								//position:'right',//坐标轴位置，移至右边
								//offset: 10,     //Y 轴相对于默认位置的偏移
								scale: true,   //刻度 自适应
								splitArea: {     //分割区域颜色
									show: false
								},
								min: min(),
								max: max(),
								interval: _interval,
								splitLine:{ //y轴网格线
									show:true,
									lineStyle: {
										color: '#cccccc',
										width: 0.2,
										type: 'dashed', //（'solid'，实线类型；'dashed'，虚线类型；'dotted',点状类型）
									}
								},
								axisLine: { //y轴坐标线设置
									show: true,
									lineStyle: {
										color: '#D3D3D3', //y轴颜色
										//width: 2,    // 坐标轴线宽
										type: 'dotted',     // 坐标轴线线的类型（'solid'，实线类型；'dashed'，虚线类型；'dotted',点状类型）
									},
								},

							axisLabel: {  //y轴标签设置
								show: true,  //是否显示
								 color: function (val) {
									val = Number(val).toFixed(2);
									if (val == preClose) {
									  return '#fff'
									}
									return val > preClose ? '#FF8C00' : '#7FFFAA';
								  },
								formatter: function (value){
									return keepTwoDecimal(value)
								}
							}
						},
						{
							type: 'value',
							gridIndex: 1,
							position:'right',//坐标轴位置，移至右边
							offset: 10,     //Y 轴相对于默认位置的偏移
							scale: true,   //刻度 自适应
							splitArea: {     //分割区域颜色
								show: false
							},
							min: min(),
							max: max(),
							interval: _interval,
							splitLine:{ //y轴网格线
								show:true,
								lineStyle: {
									color: '#cccccc',
									width: 0.2,
									type: 'dashed', //（'solid'，实线类型；'dashed'，虚线类型；'dotted',点状类型）
								}
							},
							axisLine: { //y轴坐标线设置
								show: true,
								lineStyle: {
									color: '#D3D3D3', //y轴颜色
									//width: 2,    // 坐标轴线宽
									type: 'dotted',     // 坐标轴线线的类型（'solid'，实线类型；'dashed'，虚线类型；'dotted',点状类型）
								},
							},
							axisLabel: {  //y轴标签设置
								show: true,  //是否显示
								color: function (val) {
								val = Number(val).toFixed(2);
									if (val == preClose) {
										return '#fff'
									}
									return val > preClose ? '#FF8C00' : '#7FFFAA';
								},
								formatter: function (value) {
									var resul = ratioCalculate(value, preClose);
									return Number(resul).toFixed(2) + '%'
								}
							}
						},
						{
							gridIndex: 2,  //对应坐标轴所在grid的索引
							position:'right',//坐标轴位置，移至右边
							offset: 10,
							scale: true,
							splitNumber: 2,
							splitLine:{ //y轴网格线
								show:true,
								lineStyle: {
									color: '#cccccc',
									width: 0.2,
									type: 'dashed', //（'solid'，实线类型；'dashed'，虚线类型；'dotted',点状类型）
								}
							},
							axisLine: { //y轴坐标线设置
								show: true,
								lineStyle: {
									color: '#D3D3D3', //y轴颜色
									//width: 2,    // 坐标轴线宽
									type: 'dotted',     // 坐标轴线线的类型（'solid'，实线类型；'dashed'，虚线类型；'dotted',点状类型）
								},
							},
							axisLabel: {  //y轴标签设置
								show: true,
								formatter: function (value){
									if(value != 0){
										return NumberTransform(value)
									}else{
										return 0
									}
								}
							}
						}
					],
						series: [
							{
								name: '分时',
								type: 'line',
								gridIndex: 0,
								xAxisIndex: 0,
								yAxisIndex: 0,
								data: getParamValues("close", arr),
								itemStyle: {
									normal: {
										lineStyle: {
											width: 1.2,//折线宽度
											color: "#FFFFFF"//折线颜色，改为纯白色
										},
										color: '#FFFFFF',//拐点颜色，改为纯白色
									}
								},
								markLine:{   //增加标注线
									name:'昨日收盘价',
									symbol: ['none', 'none'],
									label:{
										show:false,
										formatter:  preClose,
										position: 'start',
									},
									lineStyle: {
										color: '#4289c5',
										type: 'solid'
									},
									data: [
										{
											yAxis: preClose
										},
										{
											xAxis: '13:00',
											lineStyle: {
												color: '#fff',
												width: 0.1,
												type: 'solid'
											},
											label: {
												show: false
											}
										},
										{
											xAxis: '11:30',
											lineStyle: {
												color: '#fff',
												width: 0.1,
												type: 'solid'
											},
											label: {
												show: false
											}
										}
									]
								},
								markPoint: {
									symbol: 'arrow',
									symbolSize: 15, // 增大箭头尺寸
									
									symbolRotate: function(value) {
										return value.itemStyle && value.itemStyle.color === '#00FF00' ? 180 : 0;
									},
									itemStyle: {
										color: function(params) {
											return params.data.itemStyle ? params.data.itemStyle.color : '#FF0000';
										}
									},
									label: {
										show: false
									},
									data: rollingHighLow.highBreakPoints.concat(rollingHighLow.lowBreakPoints)
								}
							},
							{
								name: '分时均价',
								type: 'line',
								gridIndex: 0,
								xAxisIndex: 0,
								yAxisIndex: 0,
								data: getParamValues("jprice", arr),
								itemStyle: {
									normal: {
										lineStyle: {
											width: 1.2,//折线宽度
											color: "#EBEB00"//折线颜色
										},
										color: '#EBEB00',//拐点颜色
									}
								}
							},
							{
								name: 'MA250',
								type: 'line',
								gridIndex: 0,
								xAxisIndex: 0,
								yAxisIndex: 0,
								data: ma250Data,
								smooth: true,
								itemStyle: {
									normal: {
										lineStyle: {
											width: 1.2,//折线宽度，与价格线相同
											color: "#FF0000"//红色
										},
										color: '#FF0000',//拐点颜色
									}
								}
							},
							{							
								name: '分时涨幅',
								type: 'line',
								gridIndex: 1,
								xAxisIndex: 1,
								yAxisIndex: 1,
								data: getParamValues("close", arr),
								smooth: true,
								symbol: "none",
								lineStyle: { //标线的样式
									normal: {
										width: 0
									}
								},
								markLine:{ //增加标注线
									name:'竞价',
									symbol: ['none', 'none'],
									label:{
										show:false,
										position: 'start',
									},
									lineStyle: {
										color: '#fff',
										type: 'solid'
									},
									data: selectedDays > 1 ? markLines : [{
										xAxis: jm
									}]
								}
							},
							{
								name: '成交量',
								type: 'bar',
								gridIndex: 2,
								xAxisIndex: 2,
								yAxisIndex: 2,
								data: getParamValues("vol", arr),
								barWidth: selectedDays > 1 ? 1 : 2,  // 多日图表时减小柱宽
								itemStyle: {
									// 根据价格涨跌决定颜色
									color: function(params) {
										const index = params.dataIndex;
										// 获取当前价格和前一个价格
										const currentPrice = arr[index]?.close;
										const prevPrice = index > 0 ? arr[index-1]?.close : null;
										
										// 如果是第一个点，与昨收比较
										if (index === 0 || prevPrice === null) {
											return currentPrice >= preClose ? '#FF4500' : '#32CD32'; // 红涨绿跌
										}
										
										// 后续点，与前一点比较
										return currentPrice >= prevPrice ? '#FF4500' : '#32CD32'; // 红涨绿跌
									}
								},
								markLine: selectedDays > 1 ? {
									silent: true,
									symbol: 'none',
									lineStyle: {
										color: '#333333', // 改为炭黑色
										width: 0.01, // 更细的线条
										type: 'dashed'
									},
									data: window.dateBoundaries.map(b => [{
										coord: [b.index, 0]
									}, {
										coord: [b.index, 0] 
									}])
								} : null
							},
							{
								name: '前高点',
								type: 'line',
								gridIndex: 0,
								xAxisIndex: 0,
								yAxisIndex: 0,
								data: [],
								markLine: {
									symbol: ['none', 'none'],
									label: {
										show: false
									},
									lineStyle: {
										color: '#FF3333', 
										width: 1.5, 
										type: 'dashed'
									},
									data: createMarkLinesFromPoints(rollingHighLow.highPoints)
								}
							},
							{
								name: '前低点',
								type: 'line',
								gridIndex: 0,
								xAxisIndex: 0,
								yAxisIndex: 0,
								data: [],
								markLine: {
									symbol: ['none', 'none'],
									label: {
										show: false
									},
									lineStyle: {
										color: '#33FF33', 
										width: 1.5, 
										type: 'dashed'
									},

									data: createMarkLinesFromPoints(rollingHighLow.lowPoints)
								}
							},
							{
								name: '涨停标记',
								type: 'custom',
								show: gpdm === "999999",
								renderItem: function (params, api) {
									try {
										const index = api.value(0);
										if (!arr[index]) return null;

										const timeKey = arr[index].time;
										if (!timeKey) return null;

										const formattedTimeKey = timeKey.padStart(5, '0');
										const stocks = timeGroup[formattedTimeKey] || [];
										
										if (formattedTimeKey === "09:30") {
											const earlyStocks = [];
											Object.keys(earlyTimeGroup).forEach(earlyKey => {
												earlyTimeGroup[earlyKey].forEach(stock => {
													earlyStocks.push(stock);
												});
											});
											
											earlyStocks.sort((a, b) => {
												if (b.boardCount !== a.boardCount) {
													return b.boardCount - a.boardCount;
												}
												return a.time - b.time;
											});
											
											if (earlyStocks.length > 0) {
												const point930 = api.coord([index, arr[index].close]);
												if (!point930) return null;										
												const children = [];												
												if (earlyStocks.length > 0) {
													children.push({
														type: 'text',
														style: {
															text: "竞价涨停:",
															font: '14px Microsoft YaHei',
															fill: '#FFFFFF',
															textAlign: 'left',
															textVerticalAlign: 'top',
															x: point930[0],
															y: 15, // 靠近顶部
															backgroundColor: 'rgba(0,0,0,0.3)',
															padding: [2, 4, 2, 4]
														}
													});
													
													// 为每个竞价股票创建单独的文本元素
													earlyStocks.forEach((stock, idx) => {
														// 根据板数设置颜色
														let fillColor;
														if (stock.boardCount >= 4) {
															fillColor = '#FF00FF'; // 洋红色，四板及以上
														} else if (stock.boardCount === 3) {
															fillColor = '#FF0000'; // 红色，三板
														} else if (stock.boardCount === 2) {
															fillColor = '#FF7F7F'; // 淡红色，二板
														} else {
															fillColor = '#FFA500'; // 橘黄色，一板
														}
														
														const stockText = `${numToChinese(stock.boardCount)}板 ${stock.name} ${stock.timeStr.slice(0,5)} ${stock.reason || ''}`;
														
														children.push({
															type: 'text',
															style: {
																text: stockText,
																font: '14px Microsoft YaHei',
																fill: fillColor,
																textAlign: 'left',
																textVerticalAlign: 'top',
																x: point930[0],
																y: 45 + idx * 25, 
																backgroundColor: 'rgba(0,0,0,0.3)',
																padding: [2, 4, 2, 4]
															}
														});
													});
												}
												
												// 添加9:30正常涨停显示 
												if (stocks.length > 0) {
													// 标题
													const titleYPos = earlyStocks.length > 0 ? 60 + earlyStocks.length * 25 : 15;
													children.push({
														type: 'text',
														style: {
															text: "开盘涨停:",
															font: '14px Microsoft YaHei',
															fill: '#FFFFFF',
															textAlign: 'left',
															textVerticalAlign: 'top',
															x: point930[0],
															y: titleYPos,
															backgroundColor: 'rgba(0,0,0,0.3)',
															padding: [2, 4, 2, 4]
														}
													});
													
													// 为每个开盘涨停股票创建单独的文本元素
													stocks.forEach((stock, idx) => {
														// 根据板数设置颜色
														let fillColor;
														if (stock.boardCount >= 4) {
															fillColor = '#FF00FF'; // 洋红色，四板及以上
														} else if (stock.boardCount === 3) {
															fillColor = '#FF0000'; // 红色，三板
														} else if (stock.boardCount === 2) {
															fillColor = '#FF7F7F'; // 淡红色，二板
														} else {
															fillColor = '#FFA500'; // 橘黄色，一板
														}
														
														const stockText = `${numToChinese(stock.boardCount)}板 ${stock.name} ${formattedTimeKey} ${stock.reason || ''}`;
														
														children.push({
															type: 'text',
															style: {
																text: stockText,
																font: '14px Microsoft YaHei',
																fill: fillColor,
																textAlign: 'left',
																textVerticalAlign: 'top',
																x: point930[0],
																y: titleYPos + 30 + idx * 25, 
																backgroundColor: 'rgba(0,0,0,0.3)',
																padding: [2, 4, 2, 4]
															}
														});
													});
												}									
												return {
													type: 'group',
													children: children
												};
											}
										}
										
										// 处理竞价期间9:25-9:29的涨停股票显示
										let timeValue = Number(timeKey.replace(':', ''));
										if (timeValue >= 925 && timeValue < 930) {
											const thisTimeStocks = earlyTimeGroup[formattedTimeKey] || [];
											if (thisTimeStocks.length === 0) return null;
											const currentPoint = api.coord([index, arr[index].close]);
											if (!currentPoint) return null;											
											// 计算起点和终点位置
											const startPoint = currentPoint;
											const chartHeight = api.getHeight();
											const extensionPixels = 60; // 竞价期间使用固定偏移
											const extensionPercent = extensionPixels / chartHeight;
											const priceRange = max() - min();
											const priceExtension = priceRange * extensionPercent * (-1); // 向下显示
											const endPoint = api.coord([index, arr[index].close + priceExtension]);
											if (!endPoint) return null;
											
											// 创建标记显示
											return {
												type: 'group',
												children: [
													{
														// 连接线
														type: 'line',
														shape: {
															x1: startPoint[0],
															y1: startPoint[1],
															x2: endPoint[0],
															y2: endPoint[1]
														},
														style: {
															stroke: '#ffffff',
															lineWidth: 0.5,
															lineDash: [2, 3]
														}
													},
													// 为每个涨停股票创建单独的文本元素
													...thisTimeStocks.map((stock, idx) => {
														// 根据板数设置颜色
														let fillColor;
														if (stock.boardCount >= 4) {
															fillColor = '#FF00FF'; // 洋红色，四板及以上
														} else if (stock.boardCount === 3) {
															fillColor = '#FF0000'; // 红色，三板
														} else if (stock.boardCount === 2) {
															fillColor = '#FF7F7F'; // 淡红色，二板
														} else {
															fillColor = '#FFA500'; // 橘黄色，一板
														}
														
														const stockText = `${numToChinese(stock.boardCount)}板 ${stock.name} ${formattedTimeKey} ${stock.reason || ''}`;
														
														return {
															type: 'text',
															style: {
																text: stockText,
																font: '15px Microsoft YaHei',
																fill: fillColor,
																textAlign: 'center',
																textVerticalAlign: 'top',
																x: endPoint[0],
																y: endPoint[1] + 5 + idx * 25,
																backgroundColor: 'rgba(0,0,0,0.3)',
																padding: [2, 4, 2, 4]
															}
														};
													})
												]
											};
										}

										// 处理非9:30的普通时间点 
										if (stocks.length === 0) return null;
										let direction, extensionPixels;
										let basePixels = 40; 
										let prevCount = 0;
										
										if (timeValue < 1000) {
											direction = -1;
											
											// 计算当前时间距离9:31的分钟数
											const timeMinutes = Math.floor(timeValue / 100) * 60 + timeValue % 100;
											const startMinutes = 9 * 60 + 31; 
											const timeDiff = Math.max(0, timeMinutes - startMinutes);
											
											// 使用更加线性的偏移计算
											basePixels = 40; 										
											const allTimes = [];
											for (let i = 0; i < arr.length; i++) {
												if (arr[i] && timeGroup[arr[i].time.padStart(5, '0')]) {
													const iHour = Number(arr[i].time.slice(0, 2));
													const iMinute = Number(arr[i].time.slice(-2));
													if (iHour < 10) { // 只考虑10点前的涨停
														allTimes.push({
															time: arr[i].time.padStart(5, '0'),
															minutes: iHour * 60 + iMinute
														});
													}
												}
											}
											
											// 按时间排序
											allTimes.sort((a, b) => a.minutes - b.minutes);
											
											const uniqueTimes = [];
											for (let i = 0; i < allTimes.length; i++) {
												if (i === 0 || allTimes[i].time !== allTimes[i-1].time) {
													uniqueTimes.push(allTimes[i]);
												}
											}
											
											let currentPosition = 0;
											for (let i = 0; i < uniqueTimes.length; i++) {
												if (uniqueTimes[i].time === timeKey) {
													currentPosition = i + 1;
													break;
												}
											}
											
											let sameMinCount = 0;
											for (let i = 0; i < arr.length; i++) {
												if (arr[i] && timeGroup[arr[i].time.padStart(5, '0')]) {
													const iTimeKey = arr[i].time.padStart(5, '0');
													if (iTimeKey === timeKey) {
														sameMinCount++;
													}
												}
											}

											extensionPixels = basePixels + (currentPosition * 55); 
											if (sameMinCount > 1) {
												extensionPixels += (sameMinCount - 1) * 15; 
											}
											extensionPixels = Math.min(extensionPixels, 1000);
											
											console.log(`10点前 - 时间点: ${timeKey}, 位置: ${currentPosition}, 最终像素: ${extensionPixels}`);
										} else {
											const minute = Number(timeKey.slice(-2));
											const hour = Number(timeKey.slice(0, 2));
											
											const timeMinutes = hour * 60 + minute;
											const startMinutes = 10 * 60; 
											const timeDiff = Math.max(0, timeMinutes - startMinutes);
											
											const cycleIndex = Math.floor(timeDiff / 15); 
											
											direction = (cycleIndex % 2 === 0) ? 1 : -1;
											
											basePixels = 120;

											let currentCycleStocks = 0; 
											let currentStockIndex = 0;  
											

											const cycleStartMinutes = startMinutes + (cycleIndex * 15);
											const cycleEndMinutes = cycleStartMinutes + 14;

											for (let i = 0; i < arr.length; i++) {
												if (arr[i] && timeGroup[arr[i].time.padStart(5, '0')]) {
													const iHour = Number(arr[i].time.slice(0, 2));
													const iMinute = Number(arr[i].time.slice(-2));
													const iTotalMinutes = iHour * 60 + iMinute;
													
													if (iTotalMinutes >= cycleStartMinutes && iTotalMinutes <= cycleEndMinutes) {
														currentCycleStocks++;
														if (iTotalMinutes <= timeMinutes) {
															currentStockIndex++;
														}
													}
												}
											}
											if (currentStockIndex > 1) {
												extensionPixels = basePixels + ((currentStockIndex - 1) * 50); 
											} else {
												extensionPixels = basePixels; 
											}
											extensionPixels = Math.min(extensionPixels, 1000);										
											let sameMinCount = 0;
											for (let i = 0; i < arr.length; i++) {
												if (arr[i] && timeGroup[arr[i].time.padStart(5, '0')]) {
													const iTimeKey = arr[i].time.padStart(5, '0');
													if (iTimeKey === timeKey) {
														sameMinCount++;
													}
												}
											}
											
											if (sameMinCount > 1) {
												extensionPixels += (sameMinCount - 1) * 25;
											}
											console.log(`时间点: ${timeKey}, 周期: ${cycleIndex}, 序号: ${currentStockIndex}, 最终像素: ${extensionPixels}`);
										}
										const currentPoint = api.coord([index, arr[index].close]);
										if (!currentPoint) return null;
										const startPoint = currentPoint; 
										if (!startPoint) return null;
										const chartHeight = api.getHeight();
										const extensionPercent = extensionPixels / chartHeight;
										const priceRange = max() - min();
										const priceExtension = priceRange * extensionPercent * direction;
										const endPoint = api.coord([index, arr[index].close + priceExtension]);
										if (!endPoint) return null;

										return {
											type: 'group',
											children: [
												{
													type: 'line',
													shape: {
														x1: startPoint[0],
														y1: startPoint[1],
														x2: endPoint[0],
														y2: endPoint[1]
													},
													style: {
														stroke: '#ffffff',
														lineWidth: 0.5, 
														lineDash: [2, 3] 
													}
												},
												...stocks.map((stock, idx) => {

													const timeDisplay = stock.timeStr 
														? stock.timeStr.slice(0, 5) 
														: (formattedTimeKey.length === 5 
															? formattedTimeKey 
															: formattedTimeKey); 
														
													// 根据板数设置颜色
													let fillColor;
													if (stock.boardCount >= 4) {
														fillColor = '#FF00FF'; // 洋红色，四板及以上
													} else if (stock.boardCount === 3) {
														fillColor = '#FF0000'; // 红色，三板
													} else if (stock.boardCount === 2) {
														fillColor = '#FF7F7F'; // 淡红色，二板
													} else {
														fillColor = '#FFA500'; // 橘黄色，一板
													}
													const stockText = `${numToChinese(stock.boardCount)}板 ${stock.name} ${timeDisplay} ${stock.reason || ''}`;
													const yOffset = idx * 20; 
													
													return {
														type: 'text',
														style: {
															text: stockText,
															font: '14px Microsoft YaHei',
															fill: fillColor,
															textAlign: direction > 0 ? 'left' : 'center',
															textVerticalAlign: direction > 0 ? 'bottom' : 'top',
															x: direction > 0 ? endPoint[0] + 5 : endPoint[0], 
															y: direction > 0 ? endPoint[1] + yOffset : endPoint[1] - yOffset,
															backgroundColor: 'rgba(0,0,0,0.5)', 
															padding: [3, 5, 3, 5] 
														}
													};
												})
											]
										};
									} catch (e) {
										console.error('渲染涨停标记错误:', e);
										return null;
									}
								},
								data: function() {
									let lines = [];
									let isUp = true;
									let earlyStocks = []; 
									let otherStocks = []; 
									try {
										const index930 = arr.findIndex(item => item.time === '09:30');
										if (index930 >= 0) {
											let hasEarlyStocks = false;
											let hasOpenStocks = false;
											Object.keys(earlyTimeGroup).forEach(timeKey => {
												if (earlyTimeGroup[timeKey].length > 0) {
													hasEarlyStocks = true;
												}
											});
											if (timeGroup['09:30'] && timeGroup['09:30'].length > 0) {
												hasOpenStocks = true;
											}
											if (hasEarlyStocks || hasOpenStocks) {
												lines.push([index930, arr[index930].close, 1, true, 0]);
											}
										}
										Object.entries(timeGroup).forEach(([timeKey, stocks]) => {
											if (!stocks || stocks.length === 0 || timeKey === '09:30') return;
											const index = arr.findIndex(item => item.time === timeKey);
											if (index === -1) {
												console.warn('未找到时间点:', timeKey);
												return;
											}

											const timeValue = Number(timeKey.replace(':', ''));
											if (timeValue >= 931) {
												lines.push([index, arr[index].close, isUp ? 1 : -1, false, 0]);
												isUp = !isUp;
											}
										});

										console.log('涨停标记数据:', lines.length);
										return lines;
									} catch (e) {
										console.error('生成涨停标记数据错误:', e);
										return [];
									}
								}(),
								z: 10,
								gridIndex: 0,
								xAxisIndex: 0,
								yAxisIndex: 0
							},
							{
								type:'scatter',
								data: getScatterSourceData(arr),
								symbolSize:function (arg, opt){
									if (arg === 0) return 0;
									
									const timePoint = opt.name;
									const dataIndex = opt.dataIndex;
									let scatterPoint;
									if (selectedDays > 1 && arr[dataIndex]) {
										const targetDate = arr[dataIndex].date;
										const targetTime = timePoint;
										
										scatterPoint = scatterData.find(v => v.realTime === targetTime);
									} else {
										// 单日模式
										scatterPoint = scatterData.find(v => v.realTime === timePoint);
									}
									
									if (!scatterPoint) return 0;
									
									const realValue = scatterPoint.realVolumn;
									val = Math.abs(realValue);
									const info = Math.floor(val / 1000);
									const temp = selectedDays > 1 ? 8 : 12; // 多日模式下缩小点的大小
									let circle = (temp + ((info - 1) * 0.1 + ((val - info * 1000) / 1000 * 0.1)) * temp).toFixed(2);
									if (circle > 60) circle = 60;
									return circle;
								},
								itemStyle:{
									color:function (arg){
										// 找到匹配的时间点
										const timePoint = arg.name;
										const dataIndex = arg.dataIndex;
										
										// 在多日视图下，可能有相同的时间点
										let temp;
										if (selectedDays > 1 && arr[dataIndex]) {
											// 多日模式
											const targetDate = arr[dataIndex].date;
											const targetTime = timePoint;
											
											// 找到当天的对应时间点数据
											temp = scatterData.find(v => v.realTime === targetTime);
										} else {
											// 单日模式
											temp = scatterData.find(v => v.realTime === timePoint);
										}
										
										let color = 'red';
										if (temp && temp.realVolumn < 0) {
											color = 'green';
										}
										return color;
									}
								}
							}
						]
					}
					myChart.setOption(option);
					$(window).resize(myChart.resize);  
				});
			}
			
			// 获取市场信息并显示
			function fetchMarketInfo() {
				console.log("执行fetchMarketInfo函数，当前股票代码:", gpdm);

				$('#marketInfoContainer').css({
					'display': 'block',
					'position': 'absolute',
					'top': '15px',
					'right': '145px',
					'width': 'auto',
					'max-width': '70%', 
					'text-align': 'left',
					'background-color': 'transparent',
					'padding': '0 10px', 
					'z-index': '1000',
					'border': 'none',
					'border-radius': '0',
					'box-shadow': 'none',
					'color': '#eee',
					'height': 'auto'
				});
				
				$('#marketInfoPanel').css({
					'display': 'block',
					'font-size': '12px',
					'line-height': '16px'
				});
				
				// 显示加载中
				$('#marketInfoPanel').html('市场数据加载中...');
				
				// 定义市场数据变量
				var res1 = "";  // 盘面点评数据
				var res2 = "";  // 涨跌统计数据
				
				// 按照市场情绪.html的方式定义URL
				var url1 = "https://apphq.longhuvip.com/w1/api/index.php?a=DiskReview&apiv=w30&c=HomeDingPan";
				var url2 = "https://apphq.longhuvip.com/w1/api/index.php?a=ZhangFuDetail&apiv=w21&c=HomeDingPan";
				
				// 获取盘面点评数据 - 完全按照市场情绪.html的方式
				$.ajax({
					type: "get",
					url: url1,
					dataType: "text",  // 使用text而不是jsonp
					async: false,      // 使用同步请求
					cache: false,
					timeout: 3000,
					success: function(data) {
						console.log("获取盘面点评数据成功");
						res1 = data;
					},
					error: function(xhr, status, error) {
						console.error('获取盘面点评数据失败:', error);
					}
				});
				
				// 获取涨跌统计数据 - 完全按照市场情绪.html的方式
				$.ajax({
					type: "get",
					url: url2,
					dataType: "text",  // 使用text而不是jsonp
					async: false,      // 使用同步请求
					cache: false,
					timeout: 3000,
					success: function(data) {
						console.log("获取涨跌统计数据成功");
						res2 = data;
					},
					error: function(xhr, status, error) {
						console.error('获取涨跌统计数据失败:', error);
					}
				});
				
				// 处理获取到的数据并显示
				if(res1 && res2) {
					try {
						// 解析接收到的数据
						var data1 = JSON.parse(res1);
						var data2 = JSON.parse(res2);
						
						// 解析盘面点评数据
						var marketStrength = data1.info.strong || "50";  // 市场强度
						var marketComment = data1.info.sign || "";       // 市场点评
						
						// 解析涨跌统计数据
						// 获取日期
						var tradeDate = data2.date ? data2.date.substring(5) : formatCurrentDate();
						tradeDate = tradeDate.replace("-", "月") + "日";
						
						// 直接使用API返回的统计值
						var upCount = data2.info.SZJS || 0;    // 上涨家数
						var downCount = data2.info.XDJS || 0;  // 下跌家数
						var flatCount = Number(data2.info['0'] || 0);  // 平盘家数
						
						// 涨停跌停
						var limitUpCount = data2.info.SJZT || 0;    // 实际涨停
						var limitDownCount = data2.info.SJDT || 0;  // 实际跌停
						
						// 计算涨跌比
						var ratio = downCount > 0 ? (upCount / downCount).toFixed(2) : upCount.toFixed(2);
						
						var totalAmount = data2.info.qscln ? (data2.info.qscln / 10000).toFixed(0) : 0;  // 万元转为亿元
						
						// 添加市场强度显示
						var strengthValue = parseInt(marketStrength);
						var strengthColor = '#FFFFFF';
						if (strengthValue > 70) {
							strengthColor = '#FF4500'; // 强势市场，红色
						} else if (strengthValue > 50) {
							strengthColor = '#FFA500'; // 偏强市场，橙色
						} else if (strengthValue < 30) {
							strengthColor = '#32CD32'; // 弱势市场，绿色
						} else if (strengthValue < 50) {
							strengthColor = '#CCCCCC'; // 偏弱市场，淡灰色
						}
						
						var marketInfoHtml = `
							<div style="text-align:left; margin-bottom:4px;">
								<span style="color:#FFFFFF; display:inline-block; width:80px;">${tradeDate}</span> 
								成交<span style="color:#FF4500;">${totalAmount}</span>亿 
								涨<span style="color:#FF4500;">${upCount}</span> 
								跌<span style="color:#32CD32;">${downCount}</span> 
								平<span style="color:#CCCCCC;">${flatCount}</span> 
								涨停<span style="color:#FF4500;">${limitUpCount}</span> 
								跌停<span style="color:#32CD32;">${limitDownCount}</span> 
								比<span style="color:#FF4500;">${ratio}</span> 
								强度<span style="color:${strengthColor};">${strengthValue}</span>
							</div>`;
						
						$('#marketInfoPanel').html(marketInfoHtml);					
						renderMarketStatsBox(marketStrength, upCount, downCount, flatCount);
						
					} catch(e) {
						console.error('处理市场数据出现异常:', e);
						$('#marketInfoPanel').html(`<span style="color:#FF6347;">处理市场数据异常，请稍后刷新</span>`);
					}
				} else {
					$('#marketInfoPanel').html(`<span style="color:#FF6347;">获取市场数据失败，请稍后刷新</span>`);
				}
				
				function formatCurrentDate() {
					var now = new Date();
					var month = (now.getMonth() + 1).toString().padStart(2, '0');
					var day = now.getDate().toString().padStart(2, '0');
					return month + '-' + day;
				}
			}
		</script>
		<script>
			fetchMarketInfo();
			setInterval(function() {
				console.log("定时刷新市场行情数据");
				fetchMarketInfo();
			}, 30000); 
		</script>
	</body>
	
	<!-- 连板涨停功能 - 独立代码区域 -->
	<script type="text/javascript">
		var lbDt = "";
		var lbTt = "";
		var lbK = "0";
		var lbPx = "4"; 
		var lbFx = "1"; 
		var lbPanelVisible = false;
		
		// 创建连板涨停按钮并添加到页面
		function createLbztButton() {
			if(document.getElementById("lbztButton")) return;
			var btn = document.createElement("button");
			btn.id = "lbztButton";
			btn.innerHTML = "连 板 涨 停"; 
			btn.style.cssText = `
				position: fixed;
				top: 60px; /* 靠近上边缘 */
				right: 0px; /* 靠右对齐 */
				padding: 8px 5px; /* 减小水平内边距 */
				background-color: #800000;
				color: white;
				border: none;
				border-radius: 4px 0 0 4px; /* 只保留左侧圆角 */
				font-size: 14px;
				cursor: pointer;
				z-index: 9999;
				line-height: 20px; /* 添加行高设置 */
				writing-mode: vertical-lr; /* 文字竖排 */
				text-orientation: upright; /* 文字直立 */
				height: auto; /* 自适应高度 */
				width: 30px; /* 固定宽度 */
			`;
			
			btn.onclick = function() {
				toggleLbztPanel();
			};
			

			btn.onmouseover = function() {
				this.style.backgroundColor = "#a00000";
			};
			btn.onmouseout = function() {
				this.style.backgroundColor = "#800000";
			};
			
			document.body.appendChild(btn);

			makeBtnDraggable(btn);
		}

		function makeBtnDraggable(btn) {
			var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
			
			btn.onmousedown = function(e) {

				if(e.target === btn && e.type === 'click') {
					return;
				}
				

				if(e.button === 2) {
					return;
				}
				

				if(e.altKey) {
					e.preventDefault();
					e.stopPropagation();
					

					pos3 = e.clientX;
					pos4 = e.clientY;
					
					document.onmouseup = closeDragElement;
					document.onmousemove = elementDrag;
					

					btn.style.cursor = 'move';
					btn.style.boxShadow = '0 0 8px rgba(255, 255, 255, 0.7)';
				}
			};
			
			function elementDrag(e) {
				e.preventDefault();
				

				pos1 = pos3 - e.clientX;
				pos2 = pos4 - e.clientY;
				pos3 = e.clientX;
				pos4 = e.clientY;
				var newTop = (btn.offsetTop - pos2);
				var newLeft = (btn.offsetLeft - pos1);
				
				if(newTop < 0) newTop = 0;
				if(newLeft < 0) newLeft = 0;
				if(newTop > window.innerHeight - btn.offsetHeight) newTop = window.innerHeight - btn.offsetHeight;
				if(newLeft > window.innerWidth - btn.offsetWidth) newLeft = window.innerWidth - btn.offsetWidth;
				
				// 将固定的位置转换为CSS样式
				btn.style.top = newTop + "px";
				btn.style.left = newLeft + "px";
				btn.style.bottom = "auto";
				btn.style.right = "auto";
			}
			
			function closeDragElement() {
				// 停止移动
				document.onmouseup = null;
				document.onmousemove = null;
				
				// 恢复按钮样式
				btn.style.cursor = 'pointer';
				btn.style.boxShadow = 'none';
			}
		}
		
		// 初始化日期
		function initLbztDate() {
			var day = new Date();
			var mymonth = day.getMonth() + 1;
			var myday = day.getDate();
			
			if (mymonth >= 10) {
				mymonth = mymonth;
			} else {
				mymonth = "0" + mymonth;
			}
			
			if (myday >= 10) {
				myday = myday;
			} else {
				myday = "0" + myday;
			}
			
			lbTt = day.getFullYear() + "-" + mymonth + "-" + myday;
			lbDt = lbTt;
			

			
			// 默认使用当前模式(实时)
			lbK = "0";
		}
		function lbztDateChanged(dp) {
			try {
				// 立即获取新日期
				var date = dp.cal.getNewDateStr();
				console.log("[连板涨停] 选择了新日期:", date);
				if (document.getElementById("lbztDatePicker")) {
					document.getElementById("lbztDatePicker").value = date;
				}
				lbK = "1";
				lbTt = date;
				var currentDate = new Date();
				var currentFormattedDate = currentDate.Format("yyyy-MM-dd");
				var selectedDate = new Date(lbTt);
				
				if (selectedDate > currentDate) {
					console.log(`[连板涨停] 选择的是未来日期，重置为当前日期`);
					lbTt = currentFormattedDate;
					if (document.getElementById("lbztDatePicker")) {
						document.getElementById("lbztDatePicker").value = lbTt;
					}
				}
				lbztTradeday(function() {
					loadLbztData(true); // 
				});
				
			} catch (e) {
				console.error(`[连板涨停] 日期选择处理出错:`, e.message, e.stack);
			}
			return false;
		}
		function lbztTradeday(callback) {
			var checkDate = lbTt;
			console.log(`[连板涨停] 开始查找最近交易日，起始日期: ${checkDate}`);
			if (document.getElementById("lbztDatePicker")) {
				document.getElementById("lbztDatePicker").value = checkDate;
			}
			var url = "https://apphis.longhuvip.com/w1/api/index.php?Order=0&a=DailyLimitPerformance&st=1000&apiv=w26&Type=4&c=HisHomeDingPan&Index=0&PidType=1&Day=" + checkDate;
			var xhr = new XMLHttpRequest();
			
			try {
				xhr.open("GET", url, false); 
				xhr.send(null);
				
				var data = xhr.responseText;				
				if (data.length > 100 && 
					(data.indexOf('"info":[[{') !== -1 || 
					 data.indexOf('"info":[[') !== -1 || 
					 data.match(/\[\[.*?\]\]/s) || 
					 data.indexOf('"data"') !== -1)) {
					
					console.log(`[连板涨停] ${checkDate} 是有效交易日`);
					lbTt = checkDate;
					if (document.getElementById("lbztDatePicker")) {
						document.getElementById("lbztDatePicker").value = lbTt;
					}					
					if (callback && typeof callback === 'function') {
						callback();
					}
				} else {
					console.log(`[连板涨停] ${checkDate} 不是有效交易日，尝试查找前一天`);
					var prevDate = new Date(checkDate);
					prevDate.setDate(prevDate.getDate() - 1);
					var prevDateStr = prevDate.Format("yyyy-MM-dd");
					lbTt = prevDateStr;
					lbztTradeday(callback);
				}
			} catch (e) {
				console.error(`[连板涨停] 检查交易日失败:`, e.message);
				if (callback && typeof callback === 'function') {
					callback();
				}
			}
		}
		function toggleLbztPanel() {
			createLbztPanel();
			
			lbPanelVisible = !lbPanelVisible;
			var panel = document.getElementById("lbztPanel");
			
			if (lbPanelVisible) {
				panel.style.display = "block";
				lbK = "0"; // 设为实时模式				
				// 初始化为当前日期，但需要查找最近交易日
				initLbztDate();
				
				// 恢复默认排序 - 按时间降序
				lbPx = "4"; 
				lbFx = "1"; 
				lbztTradeday(function() {
					updateLbztSortButton();
					loadLbztData(true); 
				});
				
				// 开始自动刷新
				startLbztAutoRefresh();
			} else {
				panel.style.display = "none";
				stopLbztAutoRefresh();
			}
		}
		function loadLbztData(forceRefresh) {
			var contentDiv = document.getElementById("lbztContent");
			if (!contentDiv) return;
			updateLbztSortButton();
			contentDiv.innerHTML = "";
			loadLbztBoard("1");
			loadLbztBoard("2");
			loadLbztBoard("3");
			loadLbztBoard("4");
			loadLbztBoard("5");
		}
		
		function updateLbztSortButton() {
			var sortBtns = document.querySelectorAll('[id^=lbztSort]');
			for (var i = 0; i < sortBtns.length; i++) {
				sortBtns[i].innerHTML = sortBtns[i].innerHTML.replace('↑', '').replace('↓', '');
			}

			var currentBtn = document.getElementById('lbztSort' + lbPx);
			if (currentBtn) {
				currentBtn.innerHTML += lbFx === "0" ? "↑" : "↓";
			}
		}
		
		function loadLbztBoard(boardType, callback) {
			var boardName;
			var url;

			console.log(`[连板涨停] 开始加载板块 ${boardType}, 当前模式: ${lbK}, 日期: ${lbTt}`);
			
			switch (boardType) {
				case "1":
					boardName = "五板以上";
					url = lbK === "1" 
						? "https://apphis.longhuvip.com/w1/api/index.php?Order=" + lbFx + "&a=DailyLimitPerformance&st=1000&apiv=w26&Type=" + lbPx + "&c=HisHomeDingPan&Index=0&PidType=5&Day=" + lbTt
						: "https://apphq.longhuvip.com/w1/api/index.php?Order=" + lbFx + "&a=DailyLimitPerformance&st=100&apiv=w21&Type=" + lbPx + "&c=HomeDingPan&PhoneOSNew=1&PidType=5";
					break;
				case "2":
					boardName = "四板";
					url = lbK === "1"
						? "https://apphis.longhuvip.com/w1/api/index.php?Order=" + lbFx + "&a=DailyLimitPerformance&st=1000&apiv=w26&Type=" + lbPx + "&c=HisHomeDingPan&Index=0&PidType=4&Day=" + lbTt
						: "https://apphq.longhuvip.com/w1/api/index.php?Order=" + lbFx + "&a=DailyLimitPerformance&st=100&apiv=w21&Type=" + lbPx + "&c=HomeDingPan&PhoneOSNew=1&PidType=4";
					break;
				case "3":
					boardName = "三板";
					url = lbK === "1"
						? "https://apphis.longhuvip.com/w1/api/index.php?Order=" + lbFx + "&a=DailyLimitPerformance&st=1000&apiv=w26&Type=" + lbPx + "&c=HisHomeDingPan&Index=0&PidType=3&Day=" + lbTt
						: "https://apphq.longhuvip.com/w1/api/index.php?Order=" + lbFx + "&a=DailyLimitPerformance&st=100&apiv=w21&Type=" + lbPx + "&c=HomeDingPan&PhoneOSNew=1&PidType=3";
					break;
				case "4":
					boardName = "二板";
					url = lbK === "1"
						? "https://apphis.longhuvip.com/w1/api/index.php?Order=" + lbFx + "&a=DailyLimitPerformance&st=1000&apiv=w26&Type=" + lbPx + "&c=HisHomeDingPan&Index=0&PidType=2&Day=" + lbTt
						: "https://apphq.longhuvip.com/w1/api/index.php?Order=" + lbFx + "&a=DailyLimitPerformance&st=100&apiv=w21&Type=" + lbPx + "&c=HomeDingPan&PhoneOSNew=1&PidType=2";
					break;
				case "5":
					boardName = "一板";
					url = lbK === "1"
						? "https://apphis.longhuvip.com/w1/api/index.php?Order=" + lbFx + "&a=DailyLimitPerformance&st=1000&apiv=w26&Type=" + lbPx + "&c=HisHomeDingPan&Index=0&PidType=1&Day=" + lbTt
						: "https://apphq.longhuvip.com/w1/api/index.php?Order=" + lbFx + "&a=DailyLimitPerformance&st=100&apiv=w21&Type=" + lbPx + "&c=HomeDingPan&PhoneOSNew=1&PidType=1";
					break;
				default:
					if (callback) callback();
					return;
			}

			if (lbK === "1") {
				var dayParam = "&Day=" + lbTt;
				if (url.indexOf("&Day=") === -1) {
					url += dayParam;
				} else {
					url = url.replace(/&Day=[^&]+/, dayParam);
				}
				console.log(`[连板涨停] 确认历史请求URL包含正确日期: ${url}`);
			}
			
			console.log(`[连板涨停] 请求${boardName}数据: ${url}`);
			var xhr = new XMLHttpRequest();
			
			try {
				xhr.open("GET", url, false); // 使用同步请求
				xhr.send(null);
				
				if (xhr.status === 200) {
					var data = xhr.responseText;
					console.log(`[连板涨停] ${boardName}数据接收成功，长度:`, data.length);
					
					var contentDiv = document.getElementById("lbztContent");
					if (!contentDiv) {
						if (callback) callback();
						return;
					}
					
					// 创建板块div并立即添加到内容区域
					var boardDiv = document.createElement("div");
					boardDiv.id = "lbztBoard-" + boardType;
					boardDiv.style.cssText = `
						margin: 2px 0;
						border-bottom: 1px solid #333;
						padding-bottom: 15px;
					`;
					
					var titleDiv = document.createElement("div");
					titleDiv.style.cssText = `
						color: #ddd;
						font-weight: bold;
						margin-bottom: 5px;
					`;
					boardDiv.appendChild(titleDiv);
					contentDiv.appendChild(boardDiv); 
					
					// 处理数据
					processLbztBoardData(data, boardName, boardType, boardDiv, titleDiv);
					
					if (callback) callback();
				} else {
					console.error(`[连板涨停] ${boardName}请求失败:`, xhr.status);
					
					var contentDiv = document.getElementById("lbztContent");
					if (contentDiv) {
						var boardDiv = document.getElementById("lbztBoard-" + boardType) || document.createElement("div");
						boardDiv.id = "lbztBoard-" + boardType;
						
						var titleDiv = document.createElement("div");
						titleDiv.innerHTML = boardName + "：(0)";
						titleDiv.style.cssText = `
							color: #ddd;
							font-weight: bold;
							margin-bottom: 10px;
						`;
						
						boardDiv.innerHTML = '';
						boardDiv.appendChild(titleDiv);
						contentDiv.appendChild(boardDiv);
					}
					
					if (callback) callback();
				}
			} catch (e) {
				console.error(`[连板涨停] ${boardName}请求异常:`, e.message);
				
				var contentDiv = document.getElementById("lbztContent");
				if (contentDiv) {
					var boardDiv = document.getElementById("lbztBoard-" + boardType) || document.createElement("div");
					boardDiv.id = "lbztBoard-" + boardType;
					
					var titleDiv = document.createElement("div");
					titleDiv.innerHTML = boardName + "：(0)";
					titleDiv.style.cssText = `
						color: #ddd;
						font-weight: bold;
						margin-bottom: 10px;
					`;
					
					boardDiv.innerHTML = '';
					boardDiv.appendChild(titleDiv);
					contentDiv.appendChild(boardDiv);
				}
				
				if (callback) callback();
			}
		}
		
		// 处理特定板块的数据 - 增强的数据处理函数
		function processLbztBoardData(data, boardName, boardType, boardDiv, titleDiv) {
			// 添加调试信息
			console.log(`[连板涨停] 处理${boardName}数据，原始数据长度:`, data.length);
			
			// 更新日期（只在实时模式下）
			if (lbK === "0") {
				try {
					var dateMatch = data.match(/\],"(\d{4}-\d{2}-\d{2})"\]/);
					if (dateMatch && dateMatch[1]) {
						lbTt = dateMatch[1];
						lbDt = lbTt;
						
						if (document.getElementById("lbztDatePicker")) {
							document.getElementById("lbztDatePicker").value = lbTt;
						}
						console.log(`[连板涨停] 更新日期为:`, lbTt);
					}
				} catch (e) {
					console.warn(`[连板涨停] 无法从响应中提取日期:`, e.message);
				}
			}
			

			if (!data || data.length === 0 || data === "null" || data === "undefined" || 
				data.indexOf('"info":[]') !== -1 || data.indexOf('"info":[[]]') !== -1 || data.indexOf('[[]]') !== -1) {
				console.log(`[连板涨停] ${boardName}没有数据，显示为零`);
				titleDiv.innerHTML = boardName + "：(0)";
				boardDiv.innerHTML = '';
				boardDiv.appendChild(titleDiv);
				return;
			}

			try {

				console.log(`[连板涨停] ${boardName}原始数据片段:`, data.substring(0, 100) + "...");
				

				var stockData = null;
				var stocksArray = [];
				
				var stockDataMatch = data.match(/\[\[.*?\]\]/s);
				if (stockDataMatch) {
					stockData = stockDataMatch[0];
					console.log(`[连板涨停] ${boardName}方法1提取到股票数据，长度:`, stockData.length);
					
					try {
						stocksArray = JSON.parse(stockData);
						console.log(`[连板涨停] ${boardName}方法1解析成功，数据项数:`, stocksArray.length);
					} catch (err1) {
						console.warn(`[连板涨停] ${boardName}方法1解析失败:`, err1.message);
						stockData = null; // 重置失败的结果
					}
				}
				
				if (!stockData || !stocksArray.length) {
					var infoMatch = data.match(/"info":\s*(\[\[.*?\]\])/s);
					if (infoMatch && infoMatch[1]) {
						stockData = infoMatch[1];
						console.log(`[连板涨停] ${boardName}方法2提取到股票数据，长度:`, stockData.length);
						
						try {
							stocksArray = JSON.parse(stockData);
							console.log(`[连板涨停] ${boardName}方法2解析成功，数据项数:`, stocksArray.length);
						} catch (err2) {
							console.warn(`[连板涨停] ${boardName}方法2解析失败:`, err2.message);
							stockData = null;
						}
					}
				}
				
				if (!stockData || !stocksArray.length) {
					try {
						// 尝试解析完整的响应JSON
						var fullJson = JSON.parse(data);
						if (fullJson && fullJson.info && Array.isArray(fullJson.info)) {
							if (fullJson.info.length > 0 && Array.isArray(fullJson.info[0])) {
								stocksArray = fullJson.info[0];
								console.log(`[连板涨停] ${boardName}方法3解析成功，数据项数:`, stocksArray.length);
							} else {
								stocksArray = fullJson.info;
								console.log(`[连板涨停] ${boardName}方法3(备用)解析成功，数据项数:`, stocksArray.length);
							}
						}
					} catch (err3) {
						console.warn(`[连板涨停] ${boardName}方法3解析失败:`, err3.message);
					}
				}
				
				if (!stockData || !stocksArray.length) {
					try {
						var rawStockData = data.match(/\[\[([^\[\]]*(?:\[[^\[\]]*\][^\[\]]*)*)?\]\]/);
						if (rawStockData && rawStockData[0]) {
							// 清理和准备数据
							var cleanData = rawStockData[0]
								.replace(/\s+/g, '')  
								.replace(/","/g, '","')  
								.replace(/\]\],/g, '],[')  
								.replace(/\}\],/g, '],[') 
								.replace(/\}\]/g, ']]')  
								.replace(/\[\{/g, '[[')  
								.replace(/NaN/g, '"NaN"') 
								.replace(/undefined/g, '"undefined"')  
								.replace(/null/g, '"null"'); 						
							try {
								stocksArray = JSON.parse(cleanData);
								console.log(`[连板涨停] ${boardName}方法4解析成功，数据项数:`, stocksArray.length);
							} catch (err4) {
								console.error(`[连板涨停] ${boardName}方法4解析失败:`, err4.message);
								
								// 显示错误位置上下文
								if (err4 instanceof SyntaxError) {
									var errPos = err4.message.match(/position (\d+)/);
									if (errPos && errPos[1]) {
										var pos = parseInt(errPos[1]);
										console.log(`[连板涨停] ${boardName}JSON错误位置: ${pos}, 上下文:`, 
											cleanData.substring(Math.max(0, pos - 20), pos) + 
											" ➤➤➤ " + 
											cleanData.substring(pos, Math.min(cleanData.length, pos + 20)));
									}
								}
								
								// 最后手段：使用自定义解析
								var manuallyExtracted = [];
								var stockPattern = /"([^"]+)","([^"]+)",([^,]+),([^,]+),([^,]+),([^,]*)/g;
								var match;
								while (match = stockPattern.exec(cleanData)) {
									var stockItem = [
										match[1], // 代码
										match[2], // 名称
										match[3], // 数值1
										match[4], // 数值2
										match[5], // 时间戳
										match[6]  // 涨停原因
									];
									manuallyExtracted.push(stockItem);
								}
								
								if (manuallyExtracted.length > 0) {
									stocksArray = manuallyExtracted;
									console.log(`[连板涨停] ${boardName}手动解析成功，数据项数:`, stocksArray.length);
								}
							}
						}
					} catch (err5) {
						console.error(`[连板涨停] ${boardName}所有解析方法均失败:`, err5.message);
					}
				}
				
				// 如果所有方法都失败，显示无数据
				if (!stocksArray || !stocksArray.length) {
					console.log(`[连板涨停] ${boardName}没有找到有效数据，显示为零`);
					titleDiv.innerHTML = boardName + "：(0)";
					boardDiv.innerHTML = '';
					boardDiv.appendChild(titleDiv);
					return;
				}
				
				// 过滤掉无效数据项
				var validStocks = stocksArray.filter(function(stock) {
					return Array.isArray(stock) && stock.length >= 2;
				});
				
				if (validStocks.length === 0) {
					console.log(`[连板涨停] ${boardName}没有有效的股票数据，显示为零`);
					titleDiv.innerHTML = boardName + "：(0)";
					boardDiv.innerHTML = '';
					boardDiv.appendChild(titleDiv);
					return;
				}
				
				// 更新标题显示股票数量
				titleDiv.innerHTML = boardName + "：(" + validStocks.length + ")";
				
				// 清空之前可能的错误消息
				boardDiv.innerHTML = '';
				boardDiv.appendChild(titleDiv);
				
				// 添加每只股票
				validStocks.forEach(function(stock) {
					var stockDiv = document.createElement("div");
					stockDiv.style.cssText = `
						margin: 5px 0;
						padding: 5px;
						border-radius: 3px;
						cursor: pointer;
						line-height: 5px; /* 设置行高为5px */
					`;
					
					// 获取股票代码、名称
					var code = stock[0] || "";
					var name = stock[1] || "";
					
					// 格式化时间
					var timeStr = "";
					try {
						if (stock.length > 4) {
							var timestamp = parseInt(stock[4]);
							if (!isNaN(timestamp)) {
								timeStr = getLocalTime(timestamp);
							} else {
								console.warn(`[连板涨停] ${boardName}无效时间戳:`, stock[4]);
								timeStr = "未知";
							}
						} else {
							timeStr = "未知";
						}
					} catch (e) {
						console.warn(`[连板涨停] ${boardName}时间格式化失败:`, e.message);
						timeStr = "未知";
					}
					
					// 获取涨停原因
					var reason = "";
					if (stock.length > 5) {
						reason = stock[5] || "";
					}
					
					// 格式化净额
					var jeStr = "0";
					if (stock.length > 8) {
						try {
							var jeValue = parseInt(stock[8]);
							if (!isNaN(jeValue)) {
								if (Math.abs(jeValue / 100000000) >= 1) {
									jeStr = keepTwoDecimal(jeValue / 100000000) + "亿";
								} else {
									jeStr = Math.round(jeValue / 10000) + "万";
								}
							}
						} catch (e) {
							console.warn(`[连板涨停] ${boardName}净额格式化失败:`, e.message);
						}
					}
					
					// 股票信息
					stockDiv.innerHTML = `
						<span style="color:#f8d030;">${code}</span>
						<span style="color:#fff;margin-left:5px;">${name}</span>
						<span style="color:#aaa;margin-left:10px;">${timeStr}</span>
						<span style="color:#aaa;margin-left:10px;">${reason}</span>
						<span style="color:#aaa;margin-left:10px;">￥${jeStr}</span>
					`;
					
					// 添加点击事件，使用统一的处理函数
					stockDiv.setAttribute('data-code', code);
					stockDiv.addEventListener('click', handleStockClick);
					
					// 添加悬停效果
					stockDiv.onmouseover = function() {
						this.style.backgroundColor = "#222";
					};
					stockDiv.onmouseout = function() {
						this.style.backgroundColor = "transparent";
					};
					
					boardDiv.appendChild(stockDiv);
				});
			} catch (e) {
				console.error(`[连板涨停] 处理${boardName}数据出错:`, e.message, e.stack);
				
				var errorDiv = document.createElement("div");
				errorDiv.style.cssText = `
					color: #f66;
					margin: 10px 0;
					padding: 10px;
					border-left: 3px solid #f66;
					background-color: rgba(255,102,102,0.1);
				`;
				errorDiv.innerHTML = `处理${boardName}数据时出错: ${e.message}`;
				boardDiv.appendChild(errorDiv);
				
				// 更新标题状态
				titleDiv.innerHTML = boardName + "：(处理失败)";
			}
			
			if (stocksArray && stocksArray.length > 0 && gpdm === "999999" && lbK === "0") {
				// 检查是否有新的涨停股
				if (checkForNewLimitUpStocks(stocksArray)) {
					// 播放涨停提示音
					playLimitUpNotification();
				}
			}
		}
		
		// 格式化时间戳为时分秒
		function getLocalTime(nS) {
			return new Date(parseInt(nS) * 1000).Format("hh:mm:ss");
		}
		
		// 保留两位小数
		function keepTwoDecimal(num) {
			var result = parseFloat(num);
			if (isNaN(result)) {
				return 0;
			}
			result = Math.round(num * 100) / 100;
			return result;
		}
		
		// 设置排序方式
		function lbztSort(sortType) {
			if (sortType !== lbPx) {
				// 切换类别，重置排序方向
				lbPx = sortType;
				lbFx = "0";
			} else {
				// 切换排序方向
				lbFx = lbFx === "0" ? "1" : "0";
			}
			
			// 重新加载数据
			loadLbztData();
		}
		
		// 在通达信中打开股票
		function openStockInTDX(code) {
			console.log(`[连板涨停] 尝试打开股票：${code}`);
			
			try {
				// 方法1：通过treeid协议直接调用通达信（与连板.html相同的方式）
				window.location.href = 'http://www.treeid/code_' + code;
				return;
			} catch (e) {
				console.error(`[连板涨停] 方法1打开股票失败:`, e.message);
			}
			
			try {
				// 方法2：使用通达信专有协议
				var iframe = document.createElement('iframe');
				iframe.style.display = 'none';
				iframe.src = 'tdx://stockcode=' + code;
				document.body.appendChild(iframe);
				
				// 延迟删除iframe
				setTimeout(function() {
					document.body.removeChild(iframe);
				}, 1000);
			} catch (e) {
				console.error(`[连板涨停] 方法2打开股票失败:`, e.message);
			}
		}
		
		// 页面加载完成后初始化连板涨停功能
		document.addEventListener('DOMContentLoaded', function() {
			// 创建连板涨停按钮
			createLbztButton();
			
			// 确保日期控件脚本已正确加载
			if (typeof WdatePicker === "undefined") {
				console.error("[连板涨停] WdatePicker 未正确加载，尝试重新加载脚本");
				
				// 动态加载日期控件脚本
				var script = document.createElement("script");
				script.type = "text/javascript";
				script.src = "DatePicker/WdatePicker.js";
				script.onload = function() {
					console.log("[连板涨停] WdatePicker 脚本加载成功");
				};
				script.onerror = function() {
					console.error("[连板涨停] WdatePicker 脚本加载失败");
				};
				document.head.appendChild(script);
			} else {
				console.log("[连板涨停] WdatePicker 已正确加载");
			}
			
			document.addEventListener('click', function(e) {

				if (e.target && e.target.id === "lbztDatePicker" && typeof WdatePicker === "function") {
					console.log("[连板涨停] 检测到日期选择器点击，阻止事件冒泡");
					e.stopPropagation(); // 阻止事件冒泡
					
					WdatePicker({
						el: e.target.id,
						onpicking: lbztDateChanged,
						dateFmt: 'yyyy-MM-dd',
						maxDate: '%y-%M-%d'
					});
				}
			}, true); // 使用捕获阶段
		});
		function handleStockClick(event) {

			event.preventDefault();
			event.stopPropagation();
			
			// 获取股票代码
			var code = this.getAttribute('data-code');
			console.log(`[连板涨停] 点击股票: ${code}`);
			
			try {
				// 尝试使用treeid协议打开通达信 - 同连板.html中的实现
				var link = document.createElement('a');
				link.href = 'http://www.treeid/code_' + code;
				
				// 模拟点击
				document.body.appendChild(link);
				link.click();
				
				// 一些老版本浏览器支持的方法
				if (document.createEvent) {
					var event = document.createEvent('MouseEvents');
					event.initEvent('click', true, false);
					link.dispatchEvent(event);
				}
				
				// 移除链接
				setTimeout(function() {
					if (link && link.parentNode) {
						document.body.removeChild(link);
					}
				}, 100);
			} catch (e) {
				console.error(`[连板涨停] treeid协议打开失败:`, e.message);
				
				// 备用方案：使用location直接跳转
				try {
					window.location.href = 'http://www.treeid/code_' + code;
				} catch (e2) {
					console.error(`[连板涨停] 直接跳转失败:`, e2.message);
					
					// 最后方案：使用tdx协议
					try {
						var iframe = document.createElement('iframe');
						iframe.style.display = 'none';
						iframe.src = 'tdx://stockcode=' + code;
						document.body.appendChild(iframe);
						
						setTimeout(function() {
							document.body.removeChild(iframe);
						}, 1000);
					} catch (e3) {
						console.error(`[连板涨停] 所有打开方式均失败`);
						alert('无法打开股票 ' + code + '，请检查通达信是否正确安装和配置。');
					}
				}
			}
			
			return false;
		}

		// 创建连板涨停面板
		function createLbztPanel() {
			// 检查面板是否已存在
			if(document.getElementById("lbztPanel")) return;
			
			// 创建面板
			var panel = document.createElement("div");
			panel.id = "lbztPanel";
			panel.style.cssText = `
				position: fixed;
				top: 150px;
				right: 50px; /* 改为靠右侧显示 */
				width: 360px;
				max-height: 70vh;
				background-color: rgba(20, 18, 18, 0.9); /* 设置带透明度的背景色 */
				border: 1px solid #555;
				padding: 10px;
				z-index: 10000;
				//overflow-y: auto;
				display: none;
				box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
				font-size: 12px; /* 设置面板内默认字体大小 */
			`;
			
			// 创建标题和关闭按钮行
			var header = document.createElement("div");
			header.id = "lbztPanelHeader";
			header.style.cssText = `
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 5px;
				border-bottom: 1px solid #333;
				padding-bottom: 8px;
				cursor: move;
			`;
			
			// 标题和日期
			var titleDiv = document.createElement("div");
			titleDiv.style.cssText = `
				display: flex;
				align-items: center;
			`;
			
			var titleSpan = document.createElement("span");
			titleSpan.innerHTML = "涨停";
			titleSpan.style.cssText = `
				color: white;
				font-size: 10px;
				margin-right: 5px; /* 从40px改为80px，大幅增加与日期控件的间距 */
			`;
			
			// 添加刷新指示器
			var refreshIndicator = document.createElement("span");
			refreshIndicator.id = "lbztRefreshIndicator";
			refreshIndicator.innerHTML = "⟳";
			refreshIndicator.title = "数据刷新中";
			refreshIndicator.style.cssText = `
				color: #4CAF50;
				font-size: 16px;
				margin-right: 12px; /* 保持与日期控件的间距 */
				visibility: hidden; /* 改用visibility控制可见性，保留空间 */
				animation: spin 1s linear infinite;
				display: inline-block; /* 始终保持为块元素，占据空间 */
			`;
			
			// 添加旋转动画
			var animStyle = document.createElement('style');
			animStyle.textContent = `
				@keyframes spin {
					0% { transform: rotate(0deg); }
					100% { transform: rotate(360deg); }
				}
			`;
			document.head.appendChild(animStyle);
			
			var dateLabel = document.createElement("span");
			dateLabel.id = "lbztDateLabel";
			dateLabel.style.cssText = `
				color: #fff;
				font-size: 1px;
				margin-left: 1px;
				background: #222;
				padding: 3px 8px;
				border-radius: 3px;
				border: 1px solid #444;
				user-select: text;
			`;
			dateLabel.textContent = lbTt || (new Date().toISOString().slice(0,10)); // 默认显示当天日期
			
			// 添加透明度调节滑块
			var opacityLabel = document.createElement("span");
			opacityLabel.innerHTML = "透明";
			opacityLabel.style.cssText = `
				color: white;
				margin-left: 8px;
				margin-right: 1px;
			`;
			
			var opacitySlider = document.createElement("input");
			opacitySlider.type = "range";
			opacitySlider.min = "0";
			opacitySlider.max = "1";
			opacitySlider.step = "0.05";
			opacitySlider.value = "0.85"; // 默认值
			opacitySlider.style.cssText = `
				width: 80px;
				vertical-align: middle;
				-webkit-appearance: none;
				background: #444;
				height: 4px;
				border-radius: 2px;
				cursor: pointer;
			`;
			
			// 添加针对滑块的特定样式
			var styleEl = document.createElement('style');
			styleEl.textContent = `
				input[type="range"]::-webkit-slider-thumb {
					-webkit-appearance: none;
					width: 12px;
					height: 12px;
					border-radius: 50%;
					background: #ddd;
					cursor: pointer;
				}
				input[type="range"]::-moz-range-thumb {
					width: 12px;
					height: 12px;
					border-radius: 50%;
					background: #ddd;
					cursor: pointer;
					border: none;
				}
			`;
			document.head.appendChild(styleEl);
			
			var opacityValue = document.createElement("span");
			opacityValue.innerHTML = "0.85";
			opacityValue.style.cssText = `
				color: white;
				margin-left: 5px;
				min-width: 30px;
				display: inline-block;
			`;
			
			// 添加滑块事件监听并阻止事件冒泡
			opacitySlider.addEventListener('mousedown', function(e) {
				e.stopPropagation(); // 阻止事件冒泡
			});
			
			opacitySlider.addEventListener('input', function(e) {
				e.stopPropagation(); // 阻止事件冒泡
				var opacity = parseFloat(this.value).toFixed(2);
				opacityValue.innerHTML = opacity;
				panel.style.backgroundColor = `rgba(20, 18, 18, ${opacity})`;
			});		
			dateLabel.addEventListener('click', function(e) {
				if (e && e.stopPropagation) {
					e.stopPropagation();
				}
				
				console.log("[连板涨停] 日期选择器被点击");
				WdatePicker({
					el: 'lbztDatePicker', 
					onpicked: function(dp) {
						console.log("[连板涨停] 日期已选中:", dp.cal.getNewDateStr());
						lbztDateChanged(dp); 
					},
					dateFmt: 'yyyy-MM-dd',
					maxDate: '%y-%M-%d',
					qsEnabled: false, 
					autoPickDate: true, 
					autoUpdateOnChanged: true, 
					startDate: lbTt || '%y-%M-%d'
				});
			});
			
			// 关闭按钮
			var closeBtn = document.createElement("button");
			closeBtn.innerHTML = "×";
			closeBtn.style.cssText = `
				background: none;
				border: none;
				color: white;
				font-size: 20px;
				cursor: pointer;
			`;
			closeBtn.onclick = function() {
				toggleLbztPanel();
			};
			
			// 排序按钮
			var sortDiv = document.createElement("div");
			sortDiv.style.cssText = `
				margin: 1px 0;
			`;
			
			var sortByTime = document.createElement("a");
			sortByTime.id = "lbztSort4";
			sortByTime.href = "javascript:void(0)";
			sortByTime.innerHTML = "按涨停时间排序";
			sortByTime.style.cssText = `
				color: white;
				margin-right: 15px;
				text-decoration: none;
			`;
			sortByTime.onclick = function() {
				lbztSort("4");
			};
			
			var sortByReason = document.createElement("a");
			sortByReason.id = "lbztSort5";
			sortByReason.href = "javascript:void(0)";
			sortByReason.innerHTML = "按涨停原因排序";
			sortByReason.style.cssText = `
				color: white;
				margin-right: 15px;
				text-decoration: none;
			`;
			sortByReason.onclick = function() {
				lbztSort("5");
			};
			
			var sortByAmount = document.createElement("a");
			sortByAmount.id = "lbztSort8";
			sortByAmount.href = "javascript:void(0)";
			sortByAmount.innerHTML = "按主力净额排序";
			sortByAmount.style.cssText = `
				color: white;
				text-decoration: none;
			`;
			sortByAmount.onclick = function() {
				lbztSort("8");
			};
			
			// 内容区域
			var contentDiv = document.createElement("div");
			contentDiv.id = "lbztContent";
			contentDiv.style.cssText = `
				max-height: calc(70vh - 100px);
				overflow-y: auto;
			`;
			
			// 组装面板
			titleDiv.appendChild(titleSpan);
			titleDiv.appendChild(refreshIndicator); // 添加刷新指示器
			titleDiv.appendChild(dateLabel);
			titleDiv.appendChild(opacityLabel);
			titleDiv.appendChild(opacitySlider);
			titleDiv.appendChild(opacityValue);
			header.appendChild(titleDiv);
			header.appendChild(closeBtn);
			sortDiv.appendChild(sortByTime);
			sortDiv.appendChild(sortByReason);
			sortDiv.appendChild(sortByAmount);
			
			panel.appendChild(header);
			panel.appendChild(sortDiv);
			panel.appendChild(contentDiv);
			
			document.body.appendChild(panel);
			
			initLbztDate();
			
			makeDraggable(panel, header);
		}

		function makeDraggable(panel, header) {
			var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
			
			header.onmousedown = dragMouseDown;
			
			function dragMouseDown(e) {
				e = e || window.event;
				
				if (e.target.id === "lbztDatePicker" || 
					e.target.tagName.toLowerCase() === "button" || 
					e.target.type === "range" || 
					e.target.innerHTML === "透明度" ||
					e.target.parentNode.querySelector('input[type="range"]') === e.target) {
					console.log("[连板涨停] 点击了控件，不启动拖动");
					return;
				}
				
				e.preventDefault();
				pos3 = e.clientX;
				pos4 = e.clientY;
				document.onmouseup = closeDragElement;
				document.onmousemove = elementDrag;				
				document.body.style.userSelect = "none";
			}
			
			function elementDrag(e) {
				e = e || window.event;
				e.preventDefault();
				pos1 = pos3 - e.clientX;
				pos2 = pos4 - e.clientY;
				pos3 = e.clientX;
				pos4 = e.clientY;

				var newTop = panel.offsetTop - pos2;
				var newLeft = panel.offsetLeft - pos1;
				if(newTop < 0) newTop = 0;
				if(newLeft < 0) newLeft = 0;
				if(newTop > window.innerHeight - panel.offsetHeight) {
					newTop = window.innerHeight - panel.offsetHeight;
				}
				if(newLeft > window.innerWidth - panel.offsetWidth) {
					newLeft = window.innerWidth - panel.offsetWidth;
				}
				panel.style.top = newTop + "px";
				panel.style.left = newLeft + "px";
				panel.style.right = "auto";
				panel.style.bottom = "auto";
			}
			
			function closeDragElement() {
				document.onmouseup = null;
				document.onmousemove = null;
				document.body.style.userSelect = "";
			}
		}
		var lbztRefreshTimer = null;
		var lbztRefreshInterval = 300; 
		function startLbztAutoRefresh() {
			stopLbztAutoRefresh();
			
			lbztRefreshTimer = setInterval(function() {
				if (lbPanelVisible && lbK === "0") {
					console.log("[连板涨停] 定时自动刷新数据...");
					
					// 仅在交易时间内自动刷新
					var now = new Date();
					var hour = now.getHours();
					var minute = now.getMinutes();
					var timeValue = hour * 100 + minute;
					
					// 交易时间9:15-15:00
					if ((timeValue >= 915 && timeValue <= 1500) || 
						true) {
						
						var refreshIndicator = document.getElementById("lbztRefreshIndicator");
						if (refreshIndicator) {
							refreshIndicator.style.visibility = "visible"; 
							setTimeout(function() {
								refreshIndicator.style.visibility = "hidden"; 
							}, 1000);
						}				
						loadLbztData(true);
					}
				}
			}, lbztRefreshInterval);
			
			console.log("[连板涨停] 已启动自动刷新 (间隔: " + (lbztRefreshInterval/1000) + "秒)");
		}
		
		// 停止自动刷新
		function stopLbztAutoRefresh() {
			if (lbztRefreshTimer) {
				clearInterval(lbztRefreshTimer);
				lbztRefreshTimer = null;
				console.log("[连板涨停] 已停止自动刷新");
			}
		}

		// 记录已知的涨停股票时间
		var knownLimitUpStocks = {};

		// 检查是否有新的涨停股
		function checkForNewLimitUpStocks(stocksData) {
			if (!stocksData || !Array.isArray(stocksData) || stocksData.length === 0) {
				return false;
			}
			
			let hasNewLimitUp = false;
			const currentTime = Math.floor(Date.now() / 1000); // 当前时间戳（秒）
			const twoMinutesAgo = currentTime - 120; // 2分钟前的时间戳
			
			try {
				// 检查每个涨停股
				stocksData.forEach(stock => {
					if (Array.isArray(stock) && stock.length > 4) {
						const code = stock[0];
						const name = stock[1];
						const timestamp = parseInt(stock[4]);
						
						if (!isNaN(timestamp)) {
							if (timestamp >= twoMinutesAgo && 
								(!knownLimitUpStocks[code] || knownLimitUpStocks[code] < timestamp)) {
								
								console.log(`[连板涨停] 检测到新涨停股: ${name}(${code}), 时间: ${new Date(timestamp * 1000).toLocaleTimeString()}`);
								
								knownLimitUpStocks[code] = timestamp;
								hasNewLimitUp = true;
							}
						}
					}
				});
			} catch (e) {
				console.error("[连板涨停] 检查新涨停股时出错:", e);
				return false;
			}
			
			return hasNewLimitUp;
		}

		// 播放涨停提示音
		function playLimitUpNotification() {
			try {
				const audio = document.getElementById("newLimitUpAudio");
				if (audio) {
					console.log("[连板涨停] 播放涨停提示音");
					audio.play();
				}
			} catch (e) {
				console.error("[连板涨停] 播放提示音失败:", e);
			}
		}

		// === 新增：创建上证指数按钮并添加到页面 ===
		function createShIndexButton() {
			if(document.getElementById("shIndexButton")) return;
			var btn = document.createElement("button");
			btn.id = "shIndexButton";
			btn.innerHTML = "上 证 指 数"; 
			btn.style.cssText = `
				position: fixed;
				top: 200px; 
				right: 0px;
				padding: 8px 5px;
				background-color: #222222;
				color: white;
				border: none;
				border-radius: 4px 0 0 4px;
				font-size: 14px;
				cursor: pointer;
				z-index: 9999;
				line-height: 20px;
				writing-mode: vertical-lr;
				text-orientation: upright;
				height: auto;
				width: 30px;
			`;
			btn.onclick = function() {
				window.location.hash = "##999999##上证指数";
				getSource(0); // 切换到上证指数分时图
			};

			btn.onmouseover = function() {
				this.style.backgroundColor = "#a00000";
			};
			btn.onmouseout = function() {
				this.style.backgroundColor = "#800000";
			};

			document.body.appendChild(btn);

			if (typeof makeBtnDraggable === "function") {
				makeBtnDraggable(btn);
			}
		}
		document.addEventListener('DOMContentLoaded', function() {
			createLbztButton();
			createShIndexButton(); 
		});
		function setShIndexButtonActive(isActive) {
			var btn = document.getElementById("shIndexButton");
			if (!btn) return;
			if (isActive) {
				btn.style.backgroundColor = "#a00000"; // 红色
			} else {
				btn.style.backgroundColor = "#222222"; // 深灰
			}
		}

		// === 创建上证指数按钮并添加到页面 ===
		function createShIndexButton() {
			if(document.getElementById("shIndexButton")) return;

			var btn = document.createElement("button");
			btn.id = "shIndexButton";
			btn.innerHTML = "上 证 指 数"; 
			btn.style.cssText = `
				position: fixed;
				top: 200px;
				right: 0px;
				padding: 8px 5px;
				background-color: #222222;
				color: white;
				border: none;
				border-radius: 4px 0 0 4px;
				font-size: 14px;
				cursor: pointer;
				z-index: 9999;
				line-height: 20px;
				writing-mode: vertical-lr;
				text-orientation: upright;
				height: auto;
				width: 30px;
				transition: background 0.2s;
			`;
			btn.onclick = function() {
				window.location.hash = "##999999##上证指数";
				getSource(0);
				setShIndexButtonActive(true);
			};
			btn.onmouseover = function() {
				this.style.backgroundColor = "#a00000";
			};
			btn.onmouseout = function() {
				if (typeof gpdm !== "undefined" && gpdm === "999999") {
					this.style.backgroundColor = "#a00000";
				} else {
					this.style.backgroundColor = "#222222";
				}
			};

			document.body.appendChild(btn);

			if (typeof makeBtnDraggable === "function") {
				makeBtnDraggable(btn);
			}
		}

		if (typeof setShIndexButtonActive === "function") {
			setShIndexButtonActive(gpdm === "999999");
		}
		function renderMarketStatsBox(marketStrength, upCount, downCount, flatCount) {
	
			var total = upCount + downCount + flatCount;
			var upPercent = total ? (upCount / total * 100) : 0;
			var downPercent = total ? (downCount / total * 100) : 0;
			var flatPercent = total ? (flatCount / total * 100) : 0;

			var strengthColor = marketStrength > 70 ? '#FF4500' : (marketStrength > 50 ? '#FFA500' : (marketStrength < 30 ? '#32CD32' : '#CCCCCC'));
			var strengthBar = `
				<div style="margin-bottom:6px;">
					<span style="font-size:30px;color:#ccc;">市场强度</span>
					<span style="float:right;font-weight:bold;color:${strengthColor};font-size:30px;">${marketStrength}</span>
				</div>
				<div style="background:#333;height:30px;border-radius:9px;overflow:hidden;margin-bottom:10px;position:relative;">
					<div style="position:absolute;top:0;left:0;width:${marketStrength}%;height:30px;background:${strengthColor};border-radius:9px;"></div>
				</div>
			`;
			var upBar = upCount > 0 ? `<div style="position:absolute;left:0;top:0;height:100%;width:${upPercent}%;background:#FF4500;border-radius:9px 0 0 9px;"></div>` : '';
            var flatBar = flatCount > 0 ? `<div style="position:absolute;left:${upPercent}%;top:0;height:100%;width:${flatPercent}%;background:#888;"></div>` : '';
            var downBar = downCount > 0 ? `<div style="position:absolute;left:${upPercent + flatPercent}%;top:0;height:100%;width:${downPercent}%;background:#32CD32;border-radius:0 9px 9px 0;"></div>` : '';
			var upDownBar = `
				<div style="background:#222;height:18px;border-radius:9px;overflow:hidden;margin-bottom:8px;position:relative;">
					${upBar}${flatBar}${downBar}
				</div>
			`;
			var countText = `
				<div style="margin-top:4px;">
					<span style="color:#FF4500;font-weight:bold;">涨${upCount}家</span>
					<span style="color:#ccc;font-weight:bold;margin-left:12px;">平${flatCount}家</span>
					<span style="color:#32CD32;font-weight:bold;margin-left:12px;">跌${downCount}家</span>
				</div>
			`;
			document.getElementById('marketStrengthBar').innerHTML = strengthBar + upDownBar + countText;
			document.getElementById('marketUpDownBar').innerHTML = '';
			document.getElementById('marketStatsBox').style.display = 'block';
		}

		if (typeof renderMarketStatsBox === "function") {
			if (gpdm === "999999") {
				document.getElementById('marketStatsBox').style.display = 'block';
			} else {
				document.getElementById('marketStatsBox').style.display = 'none';
			}
		}

	</script>
	<div id="marketStatsBox" style="display:none; position:absolute; z-index:1001; right:500px; bottom:650px; min-width:220px; background:rgba(20,18,18,0.35); border-radius:8px; box-shadow:0 0 8px #000; padding:0 18px 10px 18px; font-size:15px; color:#fff; user-select:none; cursor:move; transform-origin: center center; transition: transform 0.1s ease;">
		<div id="marketStrengthBar"></div>
		<div id="marketUpDownBar" style="margin-top:10px;"></div>
	</div>

	<script>
	// 市场概览拖动和缩放功能
	window.addEventListener('DOMContentLoaded', function() {
		var panel = document.getElementById('marketStatsBox');
		if (!panel) return;
		var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
		var scale = 0.5; // 当前缩放比例
		var minScale = 0.5; // 最小缩放
		var maxScale = 2.0; // 最大缩放
		
		// 添加鼠标滚轮事件
		panel.addEventListener('wheel', function(e) {
			e.preventDefault();
			var delta = e.deltaY || e.detail || e.wheelDelta;
			
			// 计算新的缩放值
			var newScale = scale;
			if (delta < 0) {
				// 向上滚动，放大
				newScale = Math.min(scale * 1.1, maxScale);
			} else {
				// 向下滚动，缩小
				newScale = Math.max(scale * 0.9, minScale);
			}
			
			if (newScale !== scale) {
				scale = newScale;
				panel.style.transform = `scale(${scale})`;
				
				// 调整字体大小以保持清晰度
				var fontSize = 15 * (1 / scale);
				panel.style.fontSize = `${fontSize}px`;
				
				// 保存缩放状态
				localStorage.setItem('marketStatsBoxScale', scale);
			}
		}, { passive: false });
		
		// 恢复上次的缩放状态
		var savedScale = localStorage.getItem('marketStatsBoxScale');
		if (savedScale) {
			scale = parseFloat(savedScale);
			panel.style.transform = `scale(${scale})`;
			var fontSize = 15 * (1 / scale);
			panel.style.fontSize = `${fontSize}px`;
		}
		
		panel.onmousedown = function(e) {
			e = e || window.event;
			e.preventDefault();
			pos3 = e.clientX;
			pos4 = e.clientY;
			document.onmouseup = closeDragElement;
			document.onmousemove = elementDrag;
			document.body.style.userSelect = "none";
		};
		
		function elementDrag(e) {
			e = e || window.event;
			e.preventDefault();
			pos1 = pos3 - e.clientX;
			pos2 = pos4 - e.clientY;
			pos3 = e.clientX;
			pos4 = e.clientY;
			var newTop = panel.offsetTop - pos2;
			var newLeft = panel.offsetLeft - pos1;
			if(newTop < 0) newTop = 0;
			if(newLeft < 0) newLeft = 0;
			if(newTop > window.innerHeight - panel.offsetHeight * scale) {
				newTop = window.innerHeight - panel.offsetHeight * scale;
			}
			if(newLeft > window.innerWidth - panel.offsetWidth * scale) {
				newLeft = window.innerWidth - panel.offsetWidth * scale;
			}
			panel.style.top = newTop + "px";
			panel.style.left = newLeft + "px";
			panel.style.right = "auto";
			panel.style.bottom = "auto";
		}
		
		function closeDragElement() {
			document.onmouseup = null;
			document.onmousemove = null;
			document.body.style.userSelect = "";
		}
	});
	</script>
</script>
</html>
